【发布时间】:2009-10-03 16:05:59
【问题描述】:
我定义两个函数如何相互继承如下:
Function.prototype.inherit = function(parent){
function proto() {}
proto.prototype = parent.prototype;
this.prototype = new proto();
this.prototype.constructor = this;
this.prototype.parent = parent;
}
然后我需要定义一个 isInstance 函数,该函数的行为类似于 Java 的 instanceOf 或 PHP 的 instanceof。本质上,isInstance 可用于确定变量是否是从父函数继承的函数的实例化对象。
这是我写的:
Function.prototype.isInstance = function(func){
if(this == func){
return true;
} else{
if (this.prototype.parent == undefined || this.prototype.parent == null) {
return false;
} else {
return this.prototype.parent.isInstance(func);
}
}
}
在比较两个函数时效果很好,但在比较实例化变量时效果不佳。
Object2.inherit(Object1);
Object2.isInstance(Object1); //returns true
var obj2 = new Object2();
obj2.isInstance(Object1);// obj2.isInstance is not a function
上面的最后一种情况是我想要工作的。如何将 isInstance 添加到实例,而不仅仅是函数?对于所有 javascript 大师,我的代码是否有任何改进(可能是继承方法)?
谢谢。
【问题讨论】:
标签: javascript inheritance instanceof