2014-09-25 65 views
-1

我有以下的元典調用父函數重載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 

當然第一個是簡單的,但我不知道如何/如果我可以調用父功能,一旦它被覆蓋。

+0

以下是您的示例:http://jsfiddle.net/zu097ep4/ – dfsq 2014-09-25 14:21:10

回答

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方法。

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 
}