JavaScript 中的繼承可以通過以下幾種方式來實作:
1、原型鏈繼承:通過將子類的原型物件指向父類的實體來實作繼承,這種方式的優點是實作簡單,缺點是父類的私有屬性和方法子類是不能訪問的,
function Parent() {
this.name = 'parent';
this.age = 30;
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
2、借用建構式繼承:通過在子類的建構式中呼叫父類的建構式來實作繼承,這種方式的優點是子類可以訪問父類的私有屬性和方法,缺點是每個子類實體都會有一份父類實體的拷貝,
function Parent() {
this.name = 'parent';
this.age = 30;
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child() {
Parent.call(this);
}
3、組合繼承:通過結合原型鏈繼承和借用建構式繼承的優點來實作繼承,這種方式的優點是既可以訪問父類的私有屬性和方法,又可以避免每個子類實體都有一份父類實體的拷貝,
function Parent() {
this.name = 'parent';
this.age = 30;
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
4、ES6 Class繼承:通過使用ES6 class語法來實作繼承,
class Parent {
constructor() {
this.name = 'parent';
this.age = 30;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor() {
super();
}
}
JavaScript 中的繼承可以通過多種方式來實作,如原型鏈繼承、借用建構式繼承、組合繼承、ES6 Class繼承等,每種方式都有各自的優缺點,需要根據具體需求來選擇使用,
另外,對于JavaScript中的繼承,還有一些需要注意的點:
- 在原型鏈繼承和組合繼承中,子類的原型物件會繼承父類的原型物件,這意味著子類和父類共享同一個原型物件,如果父類原型物件上的屬性和方法發生改變,子類也會受到影響,
- 在借用建構式繼承和組合繼承中,子類的實體會有一份父類實體的拷貝,這意味著每個子類實體都有自己的父類實體,不會受到其他實體的影響,
- 在ES6 Class繼承中,父類的靜態方法和屬性會被繼承到子類,子類的實體也會繼承父類的實體方法和屬性,
選擇合適的繼承方式和組合使用,可以幫助我們更好的組織代碼,提高代碼的可維護性,
作者:yuzhihui出處:http://www.cnblogs.com/yuzhihui/ 宣告:歡迎任何形式的轉載,但請務必注明出處!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/542355.html
標籤:其他
上一篇:Three.js 進階之旅:新春特典-Rabbit craft go 🐇
下一篇:PDF劃詞翻譯
