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