ES6中的super
對象方法中的super
原型對于javascript來說非常重要,甚至可以說是javascript中最為重要的知識點。然而,很多人一看到原型就懵逼。ES5我們可以使用Object.getPrototypeOf()來返回原型對象,使用Object.setPrototypeOf()來設置原型對象。
看下面的例子:
以上代碼通過 Object.setPrototypeOf(tom, person) 設置tom的原型對象為person,通過Object.getPrototypeOf(this)返回tom的原型對象person,所以Object.getPrototypeOf(this).getSay 實際上就是person.getSay,在通過call()方法將peoson中的this指向tom作用域,實現tom繼承peoson。
相信很多人在看到Object.getPrototypeOf()和call()來調用原型時已經由懵逼遍傻逼的了。好在ES6中引入了super關鍵字來解除我們的痛苦。super引用相當于指向原型對象的指針,實際上也就是Object.getPrototypeOf(this)的值。廢話少說,我們將上面的例子改變以下:
let person = {getSay() {return 'hello'} }let tom = {getSay() {// 相當于Object.getPrototypeOf(this).getSay.call(this)return super.getSay() + ',jack';} }Object.setPrototypeOf(tom, person); console.log(tom.getSay()); // hello,jack怎么樣,是不是感覺爽了很多。不過得注意,super只能在簡寫的對象方法中使用。可是還有同學說我看到Object.setPrototypeOf(tom, person)我也惡心,別急,ES6都為你準備好了,請繼續往下看。
class中的super
在ES6之前,javascript都不支持類的概念,開發者都是通過原型實現類似類的結構。
ES5中,我們通過在繼承的函數中調用call()或者apply()方法實現繼承。
function SuperType(name) {this.name = name;this.color = ["red", "blue"]; } SuperType.prototype.sayName = function() {alert(this.name); } function SubType(name, age) {SuperType.call(this, name);this.age = age; } SubType.prototype = new SuperType(); SubType.prototype.constructor = SubType;var s1 = new SubType('ren'); s1.sayName(); console.log(s1.color); // ["red", "blue"]ES6中我們可以通過類,我們使用extends實現基類(SuperType)與派生類(SubType)之間的繼承。在派生類的constructor中調用super()即可訪問基類的構造函數。super()負責初始化this,相當于ES5中的call和apply方法。
class SuperType {constructor(name) {this.name = name;this.color = ["red", "blue"];}sayName() {alert(this.name);} } class SubType extends SuperType {constructor(name, age) {// 相當于SuperType.call(this, name);super(name);this.age = age;} } var s1 = new SubType('ren', 19); s1.sayName(); console.log(s1.color); // ["red", "blue"]Tips:
- 只可在派生類的構造函數中使用super() - 在構造函數中訪問this之前一定要調用super(),它負責初始化this。轉載于:https://www.cnblogs.com/renzhiwei2017/p/9329568.html
總結
以上是生活随笔為你收集整理的ES6中的super的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现跨excel的工作表sh
- 下一篇: operator new和operato