typescript MyObject.instanceOf()

typescript MyObject.instanceOf(),typescript,instanceof,Typescript,Instanceof,我们所有的typescript类(直接或间接)继承自: 然后,我们将一个子类声明为: export class Section extends WrObject { public static CLASS_NAME = 'Section'; className = Section.CLASS_NAME; public instanceOf(name : String) : boolean { if (this.className ===

我们所有的typescript类(直接或间接)继承自:

然后,我们将一个子类声明为:

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);
        }

}
然后,您可以检查:

if (obj.instanceOf(Section.CLASS_NAME))
一切都很好。然而,我认为如果我们能做到以下几点,它会更干净:

if (obj.instanceOf(Section))
有办法吗?或者关于更好的方法有什么建议

谢谢-戴夫

我想这可能行得通

相关的


如果您愿意接受JavaScript的原型性质,您可以使用检查原型链的
instanceof

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
你能做到。 只需将您的实现的实例替换为以下实例:

public instanceOf(cls: { CLASS_NAME: string; }) {
    return cls.CLASS_NAME === this.className || super.instanceOf(cls);
}

我认为(现在在这里找不到帖子)在typescript中不鼓励使用instanceof,因为它不准确。我是否误解了其他线索?视情况而定。您不打算在
null
上使用
instanceof
,是吗?;)+它在iFrame之间是不可靠的(如果您通过引用检查它在下面所做的工作,则每个帧中的
Foo.prototype
不同)。在webworkers中可能存在同样的问题,但我不确定是否存在空值-不。在webworkers中-到处都是。它包含在一个线程中创建的对象,发布到另一个线程,在接收线程中,我们分配proto将接收到的数据转换回一个对象。如果
foo.\uu proto\uu==foo.prototype
,那么就可以了。这就是
instanceof
所做的(或父类,即
\uuuuuu proto\uuuuuu.\uuuuuu proto\uuuuu
直到null),请注意具有相同名称的不同名称空间中的类可能是一个问题。Programming.Parent和generalogy.Parent在不同的继承树和名称空间中是非常不同的类,但是在这里会错误地测试true,因为它们的字符串名称匹配。
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
public instanceOf(cls: { CLASS_NAME: string; }) {
    return cls.CLASS_NAME === this.className || super.instanceOf(cls);
}