typescript MyObject.instanceOf()

二次信任 提交于 2019-11-29 17:16:20

问题


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


回答1:


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



回答2:


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



回答3:


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

  • How do I get the name of an object's type in JavaScript?


来源:https://stackoverflow.com/questions/24705631/typescript-myobject-instanceof

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