a house in the woods

Hi, nice to meet you.

  1. 1. 拆解class语法糖

拆解class语法糖

下面根据经babel转移后的class extends代码,说明class语法糖所作工作的要点。

  • 原代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Policeman extends Person {
    constructor(name, title) {
    super(name);
    this.title = "Officer";
    }

    sayTitle() {
    super.sayTitle()
    console.log(this.title);
    }

    static sayHi() {
    }
    }
  • 编译代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    var Policeman = /*#__PURE__*/function (_Person) {
    _inherits(Policeman, _Person);

    var _super = _createSuper(Policeman);

    function Policeman(name, title) {
    var _this;

    _classCallCheck(this, Policeman);

    _this = _super.call(this, name);
    _this.title = "Officer";
    return _this;
    }

    _createClass(Policeman, [{
    key: "sayTitle",
    value: function sayTitle() {
    _get(_getPrototypeOf(Policeman.prototype), "sayTitle", this).call(this);

    console.log(this.title);
    }
    }], [{
    key: "sayHi",
    value: function sayHi() {}
    }]);

    return Policeman;
    }(Person);
  1. _inherits(Policeman, _Person)

    1. Policemanprototype设为Person的一个实例,将Policemanprototype.constructor改写为Policeman
    2. Policeman__proto__设为Person
  2. _createSuper(Policeman)的结果可简化为下面这样,但实际上ES6class是不允许当作函数调用的,这里只是在Person是普通构造函数的情况下说明

    1
    2
    3
    function (...args) {
    return Person.apply(this, ...args)
    }
  3. _classCallCheck(this, Policeman),模拟ES6 class不允许当作函数调用,当this不是Policeman的实例就报错

  4. _super.call(this, name)执行Person的构造函数

  5. _createClass(Policeman, ...)
    _createClass除了接收Policeman构造函数外,还接受两个{ key: string, ...attrs: Descriptor }[]key为属性名,其他作为属性descriptor)参数,第一个是Policeman.prototype的属性定义数组,第二个是Policeman(即静态)的属性定义数组。
    值得注意的是,两者定义的属性都是不可枚举的enumerable: false

This article was last updated on days ago, and the information described in the article may have changed.