1.//构造函数实现继承,缺点:无法继承父类原型链上的属性和方法
// 父类
function Parent1() {
this.name = 'name';
}
Parent.prototype.say = function() {
console.log('111')
}
// 子类
function Child1 () {
Parent.call(this);
this.type = 'child';
}
2.// 原型链实现继承,子类实例化的对象属性会相互影响
// 父类
function Parent2() {
this.name = 'parent2';
this.play = [1, 2, 3]
}
// 子类
function Child2 () {
this.type = 'child2';
}
Child2.prototype = new Parent2();
let obj1 = new Child2();
let obj2 = new Child2();
obj1.play.push('5')
//此时,obj1和obj2的play属性值会一起改变,因为obj1.__proto === obj2.__proto__
- // 组合方式继承,缺点执行父类构造函数次数过多
//父类
function Parent3 () {
this.name = 'parent3';
this.play = [1, 2, 3]
}
//子类
function Child3 () {
Parent3.call(this)
this.type = 'child3'
}
Child3.prototype = new Parent3();
let obj1 = new Child3();
let obj2 = new Child3()
obj1.play.push('hah');
obj1 instanceof Child3 // true
obj1 instanceof Parent3 // true
obj1.constructor // Parent
- //优化组合方式继承,缺点实例化对象不仅是子类的实例,也是父类的实例
//父类
function Parent4 () {
this.name = 'parent4';
this.play = [1, 2, 3]
}
//子类
function Child4 () {
Parent4.call(this)
this.type = 'child4'
}
Child3.prototype = Parent4.prototype;
let obj1 = new Child4();
let obj2 = new Child4()
obj1.play.push('hah');
- //组合方式继承优化,继承最优方法
//父类
function Parent5 () {
this.name = 'parent5';
this.play = [1, 2, 3]
}
//子类
function Child5 () {
Parent4.call(this)
this.type = 'child4'
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
let obj = new Child5();
obj instanceof Child5; // true
obj instanceof Parent5; // true
obj.constructor // Child5