js实现继承的方式以及各个方式的优缺点

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);//Parent4
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);//Child5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值