typescript 打字稿 MyObject.instanceOf()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24705631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typescript MyObject.instanceOf()
提问by David Thielen
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
谢谢 - 戴夫
回答by basarat
If you are willing to accept the prototypal nature of JavaScript you can just use instanceof
which checks the prototype chain:
如果你愿意接受 JavaScript 的原型性质,你可以使用instanceof
which 检查原型链:
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
回答by Igorbek
You can do it.
Just replace your instanceOf
implementation with this one:
你能行的。只需instanceOf
用这个替换你的实现:
public instanceOf(cls: { CLASS_NAME: string; }) {
return cls.CLASS_NAME === this.className || super.instanceOf(cls);
}
回答by BrunoLM
I guess this might work Example on Playground
我想这可能适用于 Playground 示例
var getName = function(obj) : string {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(obj);
return (results && results.length > 1) ? results[1] : "";
};
class Foo
{
}
function IsTypeOf(obj: any, type: Function)
{
alert(obj.constructor.name + " == " + getName(type));
}
IsTypeOf(new Foo(), Foo);
Related
有关的