2013-04-04 76 views
0

我有一個名爲Person類:在Javascript中使用子方法調用父方法。

function Person() {} 

Person.prototype.walk = function(){ 
    alert ('I am walking!'); 
}; 
Person.prototype.sayHello = function(){ 
    alert ('hello'); 
}; 

學生類從人繼承:

function Student() { 
    Person.call(this); 
} 

Student.prototype = Object.create(Person.prototype); 

// override the sayHello method 
Student.prototype.sayHello = function(){ 
    alert('hi, I am a student'); 
} 

我要的是能夠從內部是孩子的sayHello方法調用父類方法的sayHello,像這樣:

Student.prototype.sayHello = function(){ 
     SUPER // call super 
     alert('hi, I am a student'); 
} 

所以,當我有學生的一個實例,我呼籲這種情況下sayHello方法現在應當警惕「你好」的然後'嗨,我是學生'。

什麼是一個不錯的優雅和(現代)的方式來調用超級,而不使用框架?

+0

[相關問題](http://stackoverflow.com/questions/8032566/emulate-super-in-javascript) – jbabey 2013-04-04 19:42:35

回答

2

你可以這樣做:

Student.prototype.sayHello = function(){ 
    Person.prototype.sayHello.call(this); 
    alert('hi, I am a student'); 
} 

你也可以讓它做這樣的事情更通用:

function Student() { 
    this._super = Person; 
    this._super.call(this); 
} 

... 

Student.prototype.sayHello = function(){ 
    this._super.prototype.sayHello.call(this); 
    alert('hi, I am a student'); 
} 

...雖然,TBH,我不知道認爲這是值得的抽象。