1、借助构造函数实现继承,缺点是不能继承Parent1的原型对象
function Parent1(){
this.name = "parent1";
}
function Child1(){
Parent1.call(this);
this.type = "child1";
}
2、借助原型链实现继承,缺点是Parent2的原型对象是共用的
function Parent2(){
this.name = "parent2";
this.play = [1,2,3,4];
}
function Child2(){
this.type = "child2";
}
Child2.prototype = new Parent2();
var s1= new Child2();
var s2= new Child2();
s1.play.push(4);
console.log(s1,s2);
3、组合方式实现继承,缺点是Parent3执行两次
function Parent3(){
this.name = "parent3";
this.play = [1,2,3,4];
}
function Child3(){
Parent3.call(this);
this.type = "child3";
}
Child3.prototype = new Parent3();
var s3= new Child3();
var s4= new Child3();
s1.play.push(4);
console.log(s3,s4);
4、组合方式实现继承优化一,缺点是无法区分实例是由父类创造还是子类创造
function Parent4(){
this.name = "parent3";
this.play = [1,2,3,4];
}
function Child4(){
Parent4.call(this);
this.type = "child3";
}
Child4.prototype = Parent4.prototype;
var s5= new Child4();
var s6= new Child4();
s5.play.push(4);
console.log(s5.construtor);
5、组合方式实现继承优化二(最优写法)
function Parent5(){
this.name = "parent3";
this.play = [1,2,3,4];
}
function Child5(){
Parent5.call(this);
this.type = "child3";
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.construstor = Child5;
var s7= new Child4();
var s8= new Child4();
s5.play.push(4);
console.log(s7.construtor);