typescript MyObject.instanceOf()

北城以北 提交于 2019-11-30 12:01:08

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

You can do it. Just replace your instanceOf implementation with this one:

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

I guess this might work Example on 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!