ES5的继承和ES6的继承

     ES5 的继承实质上是先创建子类的实例对象,然后再将父类的方法添加到this(Parent.apply(this))

    ES6 的继承机制完全不同,实质上是先创建父类的实例对象this(所以必须先调用父类的super()方法), 然后再用子类的构造函数修改this

具体的:ES6 通过class关键字定义类,里面有构造方法,类之间通过extends 关键字实现继承。 子类必须在constructor方法中调用super 方法。否则新建实例报错,因为子类没有自己的this 对象,而且继承了父类的this对象,然后对其进行加工.如果不调用super 方法,子类得不到 this 对象。

1.ES5

 function SuperType(){

     this.prototype = true

   }

   SuperType.prototype.getSuperValue = function(){

     return this.prototype

   }

   

   function SubType(){

     this.subproperty = false

   }

  SubType.prototype = new SubType()

  SubType.prototype.getSubValue = function (){

    return this.subproperty

  }

2.ES6 

class Human{

    constructor(name) {

        this.name = name

    }

    run(){

      console.log('RUN')

    }

  }

  class Man extends Human {

    constructor(name) {

      super(name)

      this.gender = '男'

    }

    fight(){

      console.log(" FIGHT")

    }

  }

  var User = new Man("LI Lei")

  console.log(User)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值