裝修網(wǎng)站怎么做seo 工具
上一篇:JS實現(xiàn)繼承的方式原生版
ES6的繼承
主要是依賴extends關(guān)鍵字來實現(xiàn)繼承,且繼承的效果類似于寄生組合繼承。
class Parent() {
}class Child extends Parent {constructor(x, y, color) {super(x, y);this.color = color;}
}
子類必須在constructor方法中調(diào)用super方法,否則新建實例時會報錯。這是因為子類自己的this對象,必須先通過父類的構(gòu)造函數(shù)完成塑造,得到與父類同樣的實例屬性和方法,然后再對其進行加工,加上子類自己的實例屬性和方法。如果不調(diào)用super方法,子類就得不到this對象。
class Parent {constructor() {}
}
?
class Child extends Parent {constructor() {this.num = 10//報錯super()this.num = 10//正確寫法}}
沒有 constructor 會被默認(rèn)添加,相當(dāng)于 constructor(…args) { super(…args) }
super
super的使用方式:
1、當(dāng)函數(shù)使用。作為函數(shù)調(diào)用時,代表父類的構(gòu)造函數(shù)。ES6 要求,子類的構(gòu)造函數(shù)必須執(zhí)行一次super函數(shù)。
super雖然代表了父類A的構(gòu)造函數(shù),但是返回的是子類B的實例,即super內(nèi)部的this指的是B的實例,因此super()在這里相當(dāng)于A.prototype.constructor.call(this)。
作為函數(shù)時,super()只能用在子類的構(gòu)造函數(shù)之中,用在其他地方就會報錯。
2、當(dāng)對象使用。在普通方法中,指向父類的原型對象A.prototype;在靜態(tài)方法中,指向父類。
// 當(dāng)函數(shù)使用
class A {}class B extends A {constructor() {super();}
}// 當(dāng)對象使用,當(dāng)對象使用時,相當(dāng)于引用A原型上的方法。
class A {p() {return 2;}
}class B extends A {constructor() {super();console.log(super.p()); // 2}
}let b = new B();
prototype和__proto__
類中:
子類的__proto__指向父類
子類prototype屬性的__proto__指向父類的prototype屬性
class A {
}class B extends A {
}B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
實例中:
子類實例的__proto__的__proto__指向父類的__proto__。也就說子類實例的原型的原型指向父類實例的原型
class A {
}class B extends A {
}const a = new A();
const b = new B();b.__proto__.__proto__ === a.__proto__ // true