我有一个 javascript 对象 PathDiagramElement,它的原型(prototype)成员很少。有一个 PassiveElement 对象,它的原型(prototype)是 PathDiagramElement。
也是PassiveElement,有很多自己的原型(prototype)成员。
var PathDiagramElement = function(){};
PathDiagramElement.prototype = {
myself : "Parent",
getTest : function() {
return this.myself + " function";
}
};
var PassiveElement = function() {};
PassiveElement.prototype = new PathDiagramElement();
PassiveElement.prototype = {
myself : "Child",
getTestChild : function() {
return this.myself+ " function";
}
};
var p = new PassiveElement();
alert(p.getTestChild());
alert(p.getTest());
p.getTestChild() 工作正常。但是 p.getTest() throws undefined is not a function error.
但如果我改变
PassiveElement.prototype = {
myself : "Child",
getTestChild : function() {
return this.myself+ " function";
}
};
到
PassiveElement.prototype.myself = "Child";
PassiveElement.prototype.getTestChild = function() {
return this.myself+ " function";
}
一切正常。
如何定义一个对象,它有多个自己的原型(prototype)成员并且必须使用另一个对象的原型(prototype)?
提前致谢。
最佳答案
你真的只需要两者的结合。在第一种情况下,您将用一个全新的对象覆盖 PassiveElement
的 prototype
。相反,您需要创建一个新的 PathDiagramElement
,然后为该相同 对象的新属性赋值,就像您在第二个示例中所做的那样。像这样:
PassiveElement.prototype = new PathDiagramElement();
PassiveElement.prototype.myself = "Child";
PassiveElement.prototype.getTestChild = function() {
return this.myself + " function";
}
真的没有办法解决这个问题。有扩展现有对象的便捷方法,但归根结底,您需要的是为现有对象的新属性赋值。
注意以下是等价的:
var pathDiagramEl = new PathDiagramElement();
pathDiagramEl.myself = "Child";
pathDiagramEl.getTestChild = function() {
return this.myself + " function";
}
PassiveElement.prototype = pathDiagramEl;
关于Javascript 原型(prototype) - 多个成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24375615/