js对象继承的5种方法

假设现在有a,b两个函数,b函数的实例想要访问a函数的属性和方法(b想要继承a)。

1、原型链继承

通过b函数的原型(b.prototype)指向a的实例(new a())来实现,这种继承方法就称为原型链继承。

代码实现:
这里用 parent 和 child 分别表示上述的 a 和 b

function parent(){
    this.data = '111'
}

function child(){}

child.prototype = new parent()

var c = new child()

console.log(c.data) //111

这种方式存在缺点
存在引用值共享问题,就是当a中某个属性是引用数据类型的时候,b实例如果修改了这个属性的内容则其他的b实例中这个属性也会一起改变(正常来说应该是互不干扰的,原始数据类型属性就是互不干扰的)

2、构造函数继承

通过在b函数中独立执行a( 此时a的this指向window ),然后通过call方法改变a的指向指向b实例( a.call(this) ),这样new出来的b实例就能访问到a中的属性和方法了。这种方法就称为构造函数继承。

代码实现:
这里用 parent 和 child 分别表示上述的 a 和 b

function parent(){
    this.data = '111'
}

function child(){
    parent.call(this)
}

var c = new child()

console.log(c.data)//111

这种方式同样存在缺点
使用这种方法b实例没有办法拿到a函数原型上的属性和方法。

function parent(){
    this.data = '111'
}

parent.prototype.say = function(){
    console.log("222")
}

function child(){
    parent.call(this)
}

var c = new child()

console.log(c.data)
c.say()

在这里插入图片描述
child实例调用say方法会报错。

3、组合继承(伪经典继承)

这个方法是结合了上述的两个方法,用构造函数继承中的b函数独立执行a来解决原型链继承的引用值共享问题,用原型链继承中b函数的原型指向a的实例来解决构造函数中b实例无法访问a原型上属性和方法的问题。

代码实现:

这里用 parent 和 child 分别表示上述的 a 和 b

function parent(){
    this.data = '111'
}

parent.prototype.say = function(){
    console.log("222")
}

function child(){
    parent.call(this)
}

child.prototype = new parent()

var c = new child()

console.log(c.data)
c.say()

在这里插入图片描述
伪经典继承相比于经典继承,new了两次parent,会产生了属性与方法重叠的问题。

4、寄生组合继承(经典继承)

对组合继承中b函数原型指向a实例进行修改,通过使用es5的Object.create方法来将b函数原型直接指向a的原型,省去了 new a() 的步骤。

代码实现:

这里用 parent 和 child 分别表示上述的 a 和 b

function parent(){
    this.data = '111'
}

parent.prototype.say = function(){
    console.log("222")
}

function child(){
    parent.call(this)
}

//es5之前就重写Object.create方法
if(!Object.create){ 
    Object.create = function(proto){
        function F(){}
        F.prototype = proto
        return new F()
    }
}

child.prototype = Object.create(parent.prototype)

var c = new child()

console.log(c.data)
c.say()

缺点:
通过Object.create改变b原型的指向后,b原型上原有的属性和方法就消失了。

5、es6的extends类继承

child类通过extends继承了parent类的属性和方法。

class parent {
  constructor(a){
    this.filed1 = a;
  }
  filed2 = 2;
  func1 = function(){}
}
 
class child extends parent {
    constructor(a,b) {
      super(a);
      this.filed3 = b;
    }
 
  filed4 = 1;
  func2 = function(){}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值