【发布时间】:2014-12-10 02:03:07
【问题描述】:
我试图理解 JavaScript 的原型继承。在下面的代码 sn-p 中,我尝试从具有相同名称的继承对象的函数中调用一个函数。 (本质上,我试图模仿调用“超级”方法)。
function Base() {
}
Base.prototype.hello = function() {
return "hello";
}
function Sub() {
Base.call(this);
}
Sub.prototype.hello = function() {
return this.prototype.hello() + " world";
}
Sub.prototype = Object.create(Base.prototype);
Sub.prototype.constructor = Sub;
var sub = new Sub();
alert(sub.hello());
结果不是我预期的...sub.hello() 返回"hello",但我希望它返回"hello world"。怎么了?
【问题讨论】: