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)

猜你喜欢

转载自blog.csdn.net/weixin_62364503/article/details/128186906
今日推荐