1 回答
TA贡献1836条经验 获得超13个赞
用class关键字构建的继承体系,用instanceof判断就可以了
class Animal{}
class Rabbit extends Animal{}
var rabbit = new Rabbit();
rabbit instanceof Rabbit; //true
rabbit instanceof Animal; //true
根据以上的情景,定义这个isAssignableFrom方法
Function.prototype.isAssignableFrom = function(f) {
if(!(typeof f == "function")) {
return false;
}
if(this == f) {
return true;
}
var prototype = this.prototype;
var p = f.prototype;
while(p) {
if(p == prototype) {
return true;
}
p = p.__proto__;
}
return false;
}
结果
Animal.isAssignableFrom(Rabbit); //true
Text.isAssignableFrom(Comment); //false
Node.isAssignableFrom(Comment); //true
添加回答
举报
