2013-12-13 42 views
0

首先,我想說我真的試過尋找這個,因爲我感覺好像之前已經問過這個問題。也許我使用了錯誤的術語,但是我還沒有找到任何東西。不管怎麼說,問題是:在javascript中增加繼承的功能

假設我有一個父類:

function Parent(){ 
    this.say = function(words){ 
     console.log(words); 
    }; 
} 

而且,從這個繼承的子類:

function Child(){ 
    Parent.call(this); 
} 

我想在子類有say功能除我想預先定義參數。例如,要做到這一點不理想的方式是通過向剛重寫功能:

this.say = function(){ 
    console.log("hello") 
} 

但我寧願以某種方式調用父類的發言權功能,並指定參數"hello"

會如何你這樣做嗎?或者 - 這是思考JavaScript繼承的錯誤方法,如果是這樣,你會推薦什麼?

回答

2

正確的做法是將所有實例共享的方法放在構造函數的原型和實例特定代碼中。

function Parent(){ } 

Parent.prototype.say = function(words) { 
    console.log(words); 
}; 


function Child() { 
    Parent.call(this); // apply parent constructor to instance 
} 

Child.prototype = Object.create(Parent.prototype); // establish inheritance 
Child.prototype.constructor = Child; 

Child.prototype.say = function() { // override method 
    // call parent method with specific argument 
    Parent.prototype.say.call(this, 'hello'); 
}; 

.call(和.apply)讓你調用一個函數,並明確設置什麼this應該指的是函數內部:

,如果你願意,你可以覆蓋孩子的原型任何方法。在這種情況下,我們調用父構造方法的.say方法,但由於我們也通過了this,就好像該方法在Child的實例上調用一樣。