function main()
{
this.one = 1;
}
main.prototype = {
display: function()
{
console.log(this.one);
return this;
}
};
function addition() {
main.call(this);
}
addition.prototype = new main;
addition.prototype.constructor = addition;
addition.prototype = {
add: function(x) {
this.one += x;
return this;
}
};
// addition.prototype.add = function(x)
// {
// this.one += x;
// return this;
// }
display = new addition;
display.add(3).add(5).display();
如果我用上面的addition.prototype替换注释的addition.prototype.add,它将正常工作,记录“9”。否则,在 Firebug 1.4、Firefox 3.5 中运行上述代码片段将导致“display.add(3).add(5).display is not a function”。
这两个部分有什么区别?我一直认为它们是相同的,请就差异提出建议,或/以及我如何使其与注释代码一起工作。
或者至少指出我应该在谷歌上搜索的关键字,我已经尝试了几个小时但徒劳无功。
谢谢。
最佳答案
看起来您正在用代码覆盖父级(主)的原型(prototype):
addition.prototype = {
add: function(x) {
this.one += x;
return this;
}
};
addition.prototype 现在是一个新对象,因为您刚刚分配给它。
当你这样做时:
addition.prototype.add = function(x) {
this.one += x;
return this;
}
您要向 addition.prototype
添加属性,因此保留 main 继承的 display()
函数。
顺便说一句,你从哪里得到这个代码?这是我见过的 JavaScript 中继承的最令人困惑的示例之一。
关于Javascript原型(prototype)继承区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1102617/