1. 构造方法继承
function parent() {
this.name = name;
}
function child() {
parent.call(this);
this.type = 'child';
}
console.log(new child());
parent.prototype.say = function() {}
console.log(new child().say()) // say is not a function
通过构造方法可以实现部分继承,因为它不能继承父类原型链上的属性和方法。
特点:
- 子类实例不会共享父类引用属性
- 创建子类实例时,可以向父类传递参数
- 可以实现多继承(call多个父类对象)
缺点:
- 实例并不是父类的实例,只是子类的实例
- 只能继承父类的实例属性和方法,不能继承原型属性/方法
- 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
2. 原型链继承
function parent() {
this.name = name;
this.arr = [1,2,3];
}
function child() {
this.type = 'child';
}
child.prototype = new parent();
console.log(child.prototype === new parent().__proto__); // true
var c1 = new child();
var c2 = new child();
c1.arr.push(4);
console.log(c1.arr, c2.arr); // [1,2,3,4],[1,2,3,4]
特点:
- 非常纯粹的继承关系,实例是子类的实例,也是父类的实例
- 父类新增原型方法/原型属性,子类都能访问到
- 简单,易于实现
缺点:
- 要想为子类新增属性和方法,必须要在
new Parent()
这样的语句之后执行,不能放到构造器中 - 无法实现多继承
- 来自原型对象的引用属性是所有实例共享的
- 创建子类实例时,无法向父类构造函数传参
3.组合继承
function parent() {
this.name = name;
}
function child() {
parent.call(this);
this.type = 'child';
}
child.prototype = new parent();
特点:
- 可以继承实例属性/方法,也可以继承原型属性/方法
- 既是子类的实例,也是父类的实例
- 不存在引用属性共享问题
- 可传参
- 函数可复用
缺点:
- 调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)