2012-12-19 61 views
1

我想寫一個從父類繼承的JavaScript類,重載一個方法並稍微改變它。它會檢查一些變量,如果它們被設置爲true,那麼它對父項執行相同的方法,否則它會執行一些不同的代碼。如何在Javascript中的子類中重載父類的方法?

這是我想出來的:

function Dad(name)  
{ 
    this.yell = function() 
    { 
     console.log('GRRRRRRR ' + name); 
    } 
} 

function Kid(name, age)  
{ 
    var parent = new Dad(name); 


    parent.yell = function() 
    { 
     if (age < 15) 
      console.log('BAAAAA ' + name); 
     else 
      parent.yell(); //This is the problem line, how to call this method on 
          //parent object 
    } 
    return parent; 
} 

var k = new Kid('bob', 13); 
k.yell(); 

然而,問題是,如何調用父對象的方法。

任何想法?

+0

通常的做法是將'yell'方法存儲在'Dad.prototype'中,稍後可以安全地找到它。 –

+0

當您執行'parent.yell = ...'時,存儲在該位置的原始函數將丟失,因此您需要將其存儲在某處以使用它。 –

回答

2

使用原型。它們允許你訪問超類的方法,但不需要實例化它。

然後,從子類,你可以做SuperClass.prototype.instanceMethod.call(this),這基本上是super在大多數典型的面嚮對象語言,但JS並沒有幫助你找出超類是什麼。所以你必須自己跟蹤它。在JS

// Superclass 
function Dad() {}; 
Dad.prototype.yell = function() { 
    console.log("Do your homework!"); 
} 

// Subclass 
function Kid(age) { 
    // calls the constructor of the superclass. 
    // in this case, the Dad() constructor does nothing, so it's not required here. 
    Dad.call(this); 

    // save constructor argument into this instance. 
    this.age = age; 
}; 

// Inheritance happens here, prototype is an instance of superclass 
Kid.prototype = new Dad(); 

// Make sure the constructor is properly assigned. 
Kid.prototype.constructor = Kid; 

// Override an instance method. 
Kid.prototype.yell = function() { 
    if (this.age < 18) { 
     console.log('Waaaaa, I hate homework'); 
    } else { 
     // calls the yell method of the superclass 
     Dad.prototype.yell.call(this); 
    } 
} 

// make a kid. 
var k = new Kid(13); 
k.yell(); // 'Waaaaa, I hate homework' 

// make an old kid. 
var k = new Kid(30); 
k.yell(); // 'Do your homework!' 

OO繼承可能是骯髒的,但有一些事情在那裏幫助。

僅舉幾例。

+0

我投票添加一個額外的行'Kid.prototype.constructor = Kid'來幫助Firefox正確命名對象。 –

+0

這個sorta很糟糕,因爲我不得不改變所有超類的方法來使用原型而不是this.function語法。這是否會打破使用超類的任何現有代碼? –

+0

此外,在父函數中定義了很多私有變量,即函數Dad(){var privVar,privVar2}等等。如果我切換到原型語法,所有這些都將丟失嗎? –

相關問題