2017-04-03 92 views
0

考慮下面的代碼擴展原型,繼承和超級

const A = class { 
    constructor(...args) { 
     A.prototype.constructor.apply(this, args); 
    } 
}; 

A.prototype.constructor = function(name) { 
    this.name = name; 
}; 

A.prototype.print = function() { 
    console.log(this.name); 
}; 


const B = class extends A {}; 

B.prototype.print = function() { 
    super.print(); 
    console.log('In B!'); 
}; 

super.print()B.prototype.print行拋出的'super' keyword unexpected here語法錯誤。爲什麼?

爲什麼我不能像其他語言一樣調用類超類?這樣做的正確方法是什麼?

回答

1

在JavaScript中,調用基類的實現,您可以通過名稱,明確調用它,即:

B.prototype.print = function() { 
    A.prototype.print.call(this); 
    console.log('In B!'); 
}; 
+0

這是一個真正的恥辱。在擴展這樣的原型時,有沒有「超級」支持的原因? – Spedwards

+0

最終,當將類移植到JavaScript中時,這是一個設計決定。當然,也值得注意的是其他一些語言有這個概念,但使用不同的關鍵字(例如C#中的'base') –