在覆盖javascript原型时调用父函数

时间:2014-09-25 14:05:04

标签: javascript

我有以下元代码

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

当然第一个很简单,但我不确定如果我被覆盖后如何调用父函数。

2 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是调用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
}

答案 1 :(得分: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方法。