我有一个javascript对象PathDiagramElement,它有很少的原型成员。有一个PassiveElement对象,其原型是PathDiagramElement。
PassiveElement也有很多自己的原型成员。
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()抛出undefined不是函数错误。
但如果我改变
PassiveElement.prototype = {
myself : "Child",
getTestChild : function() {
return this.myself+ " function";
}
};
到
PassiveElement.prototype.myself = "Child";
PassiveElement.prototype.getTestChild = function() {
return this.myself+ " function";
}
一切正常。
如何定义一个拥有多个原型成员的对象,以及必须使用另一个对象的原型?
提前致谢。
答案 0 :(得分:4)
你真的只需要两者的结合。在第一种情况下,您将使用全新对象覆盖prototype
PassiveElement
。相反,您需要创建一个新的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;