1. 原型链继承
原型链继承是我们用的最多的一种继承方式,就是让一个子类的原型指向父类的实例即可。
function Parent() {
this.name = 'mike';
}
function Child() {
this.age = 12;
}
Child.prototype = new Parent();
function Brother() {
this.weight = 60;
}
Brother.prototype = new Child();
有人不禁要问为什么不指向父类的原型,而是父类的一个实例?
function Parent() {
this.name = 'mike';
}
function Child() {
this.age = 12;
}
Child.prototype = Parent.prototype;
如果子类的原型直接指向父类的原型,那么子类就无法获取父类构造函数定义的属性和函数,同时修改子类的原型也会影响到父类的原型,这是违背继承的原则的。
2. 类式继承(借用构造函数)
利用call和apply在子类的构造函数中调用父类的构造函数。
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实现了Class继承,底层还是通过原型链继承实现的,只是一种新的写法。
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() {}
}