1. 原型鏈繼承
原型鏈繼承是我們用的最多的一種繼承方式,就是讓一個子類的原型指向父類的實(shí)例即可。
function Parent() {
this.name = 'mike';
}
function Child() {
this.age = 12;
}
Child.prototype = new Parent();
function Brother() {
this.weight = 60;
}
Brother.prototype = new Child();
有人不禁要問為什么不指向父類的原型,而是父類的一個實(shí)例?
function Parent() {
this.name = 'mike';
}
function Child() {
this.age = 12;
}
Child.prototype = Parent.prototype;
如果子類的原型直接指向父類的原型,那么子類就無法獲取父類構(gòu)造函數(shù)定義的屬性和函數(shù),同時修改子類的原型也會影響到父類的原型,這是違背繼承的原則的。
2. 類式繼承(借用構(gòu)造函數(shù))
利用call和apply在子類的構(gòu)造函數(shù)中調(diào)用父類的構(gòu)造函數(shù)。
function Parent(age) {
this.name = ['mike', 'jack', 'smith'];
this.age = age;
}
function Child(age) {
//Parent.call(this, age);
Parent.apply(this, [age]);
}
這樣子類就可以使用父類的屬性了。
3. Class繼承(ES6)
ES6實(shí)現(xiàn)了Class繼承,底層還是通過原型鏈繼承實(shí)現(xiàn)的,只是一種新的寫法。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {}
}
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {}
}