JS继承实现的几种方式

//继承的几种实现:
//解决方案1.通过原型继承
function Parent1(){
this.name = 'Parent1';
}
function Child1(){}
Child1.prototype = new Parent1();
//问题1:1.父类属性中存在引用类型属性时,会出现共享属性的情况(team属性被所有子类实行共享了)。
function Parent1(){
this.name = 'Parent1';//值类型
this.team = ['aa','bb','cc'];//引用类型
}
function Child1(){}
Child1.prototype = new Parent1();
var c1 =new Child1();
c1.name = 'lilei';
c1.team.push('dd');
console.info(c1.name);//lilei
console.info(c1.team);//["aa", "bb", "cc", "dd"]
var c2 = new Child1();
console.info(c2.name);//Parent1
console.info(c2.team);//["aa", "bb", "cc", "dd"]
//问题2.无法在不影响对象实例的情况下,对父类的构造函数传参
function Parent1(name){
this.name = name;
}
function Child1(){}
Child1.prototype = new Parent1('aa');
var c1 = new Child1();
console.info(c1.name);
Child1.prototype = new Parent1('bb');
var c2 = new Child1();
console.info(c2.name);
//问题3:此时子类的构造函数指向父类的构造函数
function Parent1(){
this.name = 'Parent1';
}
function Child1(){}
Child1.prototype = new Parent1();
console.info(new Child1().constructor);//ƒ Parent1(){ this.name = 'Parent1';}

//解决方案2.通过借用构造函数
function Parent2(){
this.name = 'Parent2';
}
function Child2(){
Parent2.call(this);
this.type = 'Child2';
}
//解决了父属性存在引用类型的问题
function Parent2(){
this.team = ['aa','bb','cc'];
}
function Child2(){
Parent2.call(this);
}
var c1 = new Child2();
c1.team.push('dd');
console.info(c1.team);//["aa", "bb", "cc", "dd"]
var c2 = new Child2();
console.info(c2.team);// ["aa", "bb", "cc"]
//问题:1、父类原型中的方法,子类不可见2.方法在构造函数中定义,函数无法复用。

//解决方案3.使用组合式继承
function Parent3(){
this.name = 'Parent3';
}
Parent3.prototype.talk = function(){
console.info('parent say hi');
}
function Child3(){
Parent3.call(this);//第二次调用Parent3()
this.type = 'Child3'
}
Child3.prototype = new Parent3();//第一次调用Parent3()
Child3.prototype.constructor = Child3();//解决构造函数问题
//问题:1.调用两次构造函数,(在新对象上创建的实例属性'name',屏蔽了原型中的同名属性)

//解决方案4:使用组合继承方法优化
function Parent4(){
this.name = 'Parent3';
}
function Child4(){
Parent4.call(this);//第二次调用Parent3()
this.type = 'Child3'
}
Child4.prototype = Parent4.prototype;
Child3.prototype.constructor = Child3();
//问题:Child4.prototype = Parent4.prototype;该句是将子类的原型直接指向了父类的原型,而从继承的本质上讲应该是父类的原型是子类原型的基础,因此使用到原型继承(克罗克富德提出)的写法Object.create().由此,产生了方案五:寄生组合继承。

//解决方案5:使用寄生组合继承方法
function Parent4(){
this.name = 'Parent3';
}
function Child4(){
Parent4.call(this);//第二次调用Parent3()
this.type = 'Child3'
}
Child4.prototype = Object.create(Parent4.prototype);
Child3.prototype.constructor = Child3();
原文地址:https://www.cnblogs.com/codeww/p/8457895.html