【发布时间】:2011-08-31 22:50:05
【问题描述】:
我在弄乱原型链并注意到一些我无法解释的东西。我仍在学习所有这些,所以这可能是我犯的错误。我正在尝试做一些多重继承,就像许多其他人一样。我注意到原型对象看起来很像哈希/字典,我想,为什么不使用类似 underscore.extend 的东西将多个原型对象合并为一个对象。
function A(){this.value="A";};
A.prototype.funcA = function (){console.log(this.value);}
function B(){this.value="B";};
B.prototype.funcB = function (){console.log(this.value);}
function C(){
// fix constructor
this.constructor = C;
// 'inherit' properties
A.call(this);
B.call(this);
};
// gobble up the prototype chains of A and B
C.prototype = new underscore.extend(A.prototype,B.prototype);
C.prototype.funcC = function (){console.log(this.value);}
var c = new C();
> c instanceof C
true
> c instanceof A
true
> c instanceof B
false
我真的很惊讶在这里得到一个真实的。谁能解释这里发生了什么?
更新 按照建议,我从代码中删除了下划线的扩展方法,这样效果更好。谢谢!
function extend(destination, source) {
for (var property in source) {
if (source.hasOwnProperty(property)) {
destination[property] = source[property];
}
}
return destination;
};
function A(){this.value="A";};
A.prototype.funcA = function (){console.log(this.value);}
function B(){this.value="B";};
B.prototype.funcB = function (){console.log(this.value);}
function C(){
this.constructor = C;
A.call(this);
B.call(this);
};
var destination = {};
destination = extend(destination,A.prototype);
destination = extend(destination,B.prototype);
C.prototype = destination;
C.prototype.funcC = function (){console.log(this.value);}
var c = new C();
> c
{ constructor: [Function: C], value: 'B' }
> c instanceof A
false
> c instanceof B
false
> c instanceof C
true
【问题讨论】:
-
我想知道从该范围调用构造函数是否会将祖先标记为javascript引擎中的“实例”,但我找不到任何表明这一点的东西。如果您不调用 underscore.extend 它仍然返回 true 吗?如果不调用父构造函数,它仍然返回 true 吗?
-
我想知道为什么您没有看到
new underscore.extend(…)的错误。extend()返回一个对象,而不是构造函数,所以它不应该用new实例化它-据我所知...... -
> A.prototype { funcA: [Function], funcB: [Function], funcC: [Function] }看起来原型在 underscore.extend 调用之后被改变了。有趣的。我猜我会用艰难的方式合并它们:) -
@SneakyWombat:
extend()修改并返回第一个参数。因此,您使用 B.prototype 扩展 A.prototype,并使用与 C.prototype 相同的对象(A.prototype),然后添加到相同的对象。因此,A.prototype 包含所有三个func*方法是有道理的。但我还是不太明白为什么new行没有抛出 TypeError -
我确定我在这里做了几件我不应该做的事情,但这就是你学习的方式对吗? :) 感谢所有 cmets/提示!
标签: javascript function-prototypes