【问题标题】:Call Prototype's Method from Inheriting Object's Function [duplicate]从继承对象的函数调用原型的方法[重复]
【发布时间】: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"。怎么了?

【问题讨论】:

    标签: javascript inheritance


    【解决方案1】:

    在这里,您在 Sub 原型上设置了一个 hello 属性,但该原型在下一行被 Object.create 覆盖。

    Sub.prototype.hello = function() {
        return this.prototype.hello() + " world";
    }
    Sub.prototype = Object.create(Base.prototype);
    

    切换这些语句的顺序,并在Sub hello 方法中使用对Base 的引用。代码应如下所示:

    function Base() {
    }
    Base.prototype.hello = function() {
        return "hello";
    }
    
    function Sub() {
        Base.call(this);
    }
    Sub.prototype = Object.create(Base.prototype);
    Sub.prototype.hello = function() {
        return Base.prototype.hello() + " world";
    }
    Sub.prototype.constructor = Sub;
    
    var sub = new Sub();
    console.log(sub.hello()); // "hello world"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多