class extends语法糖的实质

2018-10-17  本文已影响16人  月肃生

class的使用

通过class创建类(实质是函数)

class Person {
  static type='animal'
  constructor(name){
    this.name = name
  }
  getName(){
    return this.name
  }
}
class Chinese extends Person {
  constructor(name, age){
    super(name)
    this.name = name
    this.age = age
  }
}

分析

对js原型链熟悉的人应该能很快理解(ps: js:原型、继承总结)

  1. 原型链的constructor指向函数本身,所以constructor里写的就是函数体内容
  2. getName相当于Person.prototype.getName
  3. static是个提案,相当于Person.type='animal'
  4. super()就是构造继承的Person.apply(this)

源码

通过转成原始代码应该是这样的

function Person(name) {
  this.name = name
}
Person.type = 'animal'
Person.prototype = {
  constructor: Person,
  getName: function(){
    return this.name
  }
}

function Chinese (name, age) {
  Person.apply(this, arguments)
  this.age = age
}

// 组合继承
Chinese.prototype = new Person()

// 寄生组合继承
(function(){
  function Mid(){}
  Mid.prototype = Person.prototype
  Chinese.prototype = new Mid()
  Chinese.prototype.constructor = Mid
})()

Chinese.prototype.constructor = Chinese
上一篇 下一篇

猜你喜欢

热点阅读