【发布时间】:2013-02-26 19:56:58
【问题描述】:
根据 Douglas Crockford 的说法,我可以使用 http://javascript.crockford.com/prototypal.html 之类的东西(稍作调整)......但我对 jQuery 的处理方式很感兴趣。使用 $.extend 是一种好习惯吗?
我有 4 节课:
var A = function(){ }
A.prototype = {
name : "A",
cl : function(){
alert(this.name);
}
}
var D = function(){}
D.prototype = {
say : function(){
alert("D");
}
}
var B = function(){} //inherits from A
B.prototype = $.extend(new A(), {
name : "B"
});
var C = function(){} //inherits from B and D
C.prototype = $.extend(new B(), new D(), {
name : "C"
});
var o = new C();
alert((o instanceof B) && (o instanceof A) && (o instanceof C)); //is instance of A, B and C
alert(o instanceof D); //but is not instance of D
所以,我可以从 A、B、C 和 D 调用每个方法、属性...。问题来了,当我想测试 o 是否是 D 的实例时?我该如何克服这个问题?
【问题讨论】:
-
请注意,在实践中,在鸭子类型语言中,您很少关心对象是否是某事物的实例。为什么要检查 instanceof D?请注意,通常您真正需要的是en.wikipedia.org/wiki/Mixin
-
多重继承不适用于
instanceof,因为对象只能有一个线性原型链。
标签: javascript jquery multiple-inheritance extend