Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

typescript MyObject.instanceOf()

All of our typescript classes inherit (directly or indirectly) from:

export class WrObject {
    className:string;

    public instanceOf(name : String) : boolean {
        return this.className === name;
    }
}

We then declare a subclass as:

export class Section extends WrObject {
    public static CLASS_NAME = 'Section';
    className = Section.CLASS_NAME;

        public instanceOf(name : String) : boolean {
            if (this.className === name)
                return true;
            return super.instanceOf(name);
        }

}

And you can then check with:

if (obj.instanceOf(Section.CLASS_NAME))

It all works great. However, I think it would be cleaner if we could do:

if (obj.instanceOf(Section))

Is there any way to do that? Or any suggestions as to a better approach?

thanks - dave

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are willing to accept the prototypal nature of JavaScript you can just use instanceof which checks the prototype chain:

class Foo{}
class Bar extends Foo{}
class Bas{}

var bar = new Bar();

console.log(bar instanceof Bar); // true
console.log(bar instanceof Foo); // true
console.log(bar instanceof Object); // true

console.log(bar instanceof Bas); // false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...