【问题标题】:Call parent function when overriding javascript prototype [duplicate]覆盖javascript原型时调用父函数[重复]
【发布时间】:2014-11-20 08:22:59
【问题描述】:

我有以下元代码

var Parent = function(){}
Parent.prototype.doSomething = function(){
  console.log("As a parent I did like a parent");
}

var Child = function(){}
Child.prototype = new Parent();
Child.prototype.doSomething = function(){
  console.log("As a child I did like a child");
  //This is where I am not sure what to put
}

我想要的 2 行

As a child I did like a child
As a parent I did like a parent

当然第一个很简单,但我不确定如何/是否可以在父函数被覆盖后调用它。

【问题讨论】:

标签: javascript


【解决方案1】:

您可以通过执行以下操作来保存基本方法:

var Parent = function () {}
Parent.prototype.doSomething = function () {
    alert("As a parent I did like a parent");
}

var Child = function () {}
Child.prototype = new Parent();
Child.prototype.doSomething = (function () {
    // since this is an IIFE - Child.prototype.doSomething will refer to the base
    // implementation. We haven't assigned this new one yet!
    var parent_doSomething = Child.prototype.doSomething;   
    return function () {
        alert("As a child I did like a child");
        parent_doSomething();
    }
})();

var c = new Child();
c.doSomething();

这样做的好处是不必担心父母是谁。尽管您可能应该检查父级是否具有doSomething 方法。

【讨论】:

    【解决方案2】:

    一种方法是调用Parent.prototype.method.call(this, arg1, arg2, ...)。 您可以在HERE 中阅读有关超级调用的更多信息。

    var Child = function(){}
    Child.prototype = new Parent();
    
    Child.prototype.doSomething = function(){
      console.log("As a child I did like a child");
      Parent.prototype.doSomething.call(this); //with this line
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2014-10-23
      • 2010-09-22
      • 2021-01-26
      相关资源
      最近更新 更多