拆解class语法糖
下面根据经babel转移后的class extends代码,说明class语法糖所作工作的要点。
原代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14class 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
29var 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);
_inherits(Policeman, _Person)- 将
Policeman的prototype设为Person的一个实例,将Policeman的prototype.constructor改写为Policeman - 将
Policeman的__proto__设为Person
- 将
_createSuper(Policeman)的结果可简化为下面这样,但实际上ES6的class是不允许当作函数调用的,这里只是在Person是普通构造函数的情况下说明1
2
3function (...args) {
return Person.apply(this, ...args)
}_classCallCheck(this, Policeman),模拟ES6 class不允许当作函数调用,当this不是Policeman的实例就报错_super.call(this, name)执行Person的构造函数_createClass(Policeman, ...),_createClass除了接收Policeman构造函数外,还接受两个{ key: string, ...attrs: Descriptor }[](key为属性名,其他作为属性descriptor)参数,第一个是Policeman.prototype的属性定义数组,第二个是Policeman(即静态)的属性定义数组。
值得注意的是,两者定义的属性都是不可枚举的enumerable: false