闲来无事,看了下babel对于Javascript ES6中的类与继承的实现,整理一下。???
大家都知道ES6的Class是语法糖,Javascript本身是没有类的概念的,要实现继承的概念可以使用原型链的方式。既然是语法糖,那就看看babel编译成ES5的代码就可以了。
举个?:
class Human { constructor(name) { this.name = name; } say() { console.info(`I am ${ this.name}`); } static cry() { console.info('crying ~'); }}class Dancer extends Human { constructor(name) { super(name); } dance() { console.info(`${ this.name} is dancing ~`); }}class SuperMan extends Human { constructor(name, level) { super(name); this.level = level; } say() { console.info(`I am ${ this.name}, whose level is ${ this.level}`); } fly() { console.info(`${ this.name} is flying ~ so cool.`); }}复制代码
基于这个栗子的类定义以及继承:
const man = new Human('葫芦娃');const dancer = new Dancer('小明');const superman = new SuperMan('小魔仙', 10);console.info('man #######################');man.say();Human.cry();console.info('dancer #######################');dancer.say();dancer.dance();Dancer.cry();console.info('superman #######################');superman.say();superman.fly();SuperMan.cry();复制代码
上述执行结果如下:
proto , [[prototype]] and prototype
在开始前,需要分清三个概念**proto, [[prototype]] and prototype**。其中[[prototype]]是规范中定义的对象的原型属性指向一个原型对象,但是这个属性不能被直接access到,因此一个不在规范中的__proto__属性被实现用来方便得到一个对象的原型对象,因为不在规范中所以不能保证一定有这个属性,babel的编译的结果中也做了相应的兼容处理。每个对象都有[[prototype]],但是函数还有一个prototype属性,这个属性的用于在构造函数被new方法调用的时候生成构造的对象的原型对象。Javascript的原型链是[[prototype]]属性(或者说__proto__)的指向不是prototype,prototype用于构造__proto__指向的对象。
简单来说:
The prototype is a property on a constructor function that sets what will become the proto property on the constructed object.
类的定义(Class)
class Human { constructor(name) { this.name = name; } say() { console.info(`I am ${ this.name}`); } static cry() { console.info('crying ~'); }}复制代码
Babel compiled result(保留了主要的方法):
'use strict';var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; };}();var Human = function () { function Human(name) { this.name = name; } _createClass(Human, [ { key: 'say', value: function say() { console.info('I am ' + this.name); } } ], [ { key: 'cry', value: function cry() { console.info('crying ~'); } } ]); return Human;}();复制代码
这里可以看到Class本质上是一个构造函数,?中就是Human函数,其中在Class的constructor中通过this.name定义的属性name是之后在构造的对象【这里我们成为instance,方便之后说明】上的属性,被编译成熟悉的:
function Human(name) { this.name = name; }复制代码
在?中,say属性是定义在instance的[[prototype]]对象上的属性,静态属性cry是定义在类本身,也就是Human函数上,这两种属性的定义,使用的**__createClass**方法:
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; };}();复制代码
_createClass 方法是一个立即执行函数,返回一个接收参数(Constructor, protoProps, staticProps)的方法。 其中第一个参数Constructor是构造函数(Human),第二个参数protoProps是需要被定义到instance的[[prototype]]上的属性的数组,staticProps是需要定义在Constructor【构造函数,这里用Constructor方便说明】上的属性的数组。其中使用definedProperties方法:
function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }复制代码
遍历数组,使用Object.defineProperty方法定义属性到target上。
Class的语法糖的实现就是这么简单,接下来看下extends的语法糖。
类的继承(extends)
class Human { constructor(name) { this.name = name; } say() { console.info(`I am ${ this.name}`); } static cry() { console.info('crying ~'); }}class Dancer extends Human { constructor(name) { super(name); } dance() { console.info(`${ this.name} is dancing ~`); }}复制代码
Babel compiled result:
var Human = function () { function Human(name) { this.name = name; } _createClass(Human, [{ key: 'say', value: function say() { console.info('I am ' + this.name); } }], [{ key: 'cry', value: function cry() { console.info('crying ~'); } }]); return Human;}();var Dancer = function (_Human) { _inherits(Dancer, _Human); function Dancer(name) { return _possibleConstructorReturn( this, (Dancer.__proto__ || Object.getPrototypeOf(Dancer)).call(this, name) ); } _createClass(Dancer, [{ key: 'dance', value: function dance() { console.info(this.name + ' is dancing ~'); } }]); return Dancer;}(Human);复制代码
这里需要注意的是**_inherits和_possibleConstructorReturn**两个新出现的方法:
_inherits
可以看到_inherits方法的作用其实就是做了Dancer.prototype.proto = Human.prototype 和 Dancer.proto = Human两件事:
Dancer.prototype.__proto__ === Human.prototype // true复制代码
的作用是使Human的定义在构造的对象的原型对象上的属性,被继承到Dancer构造的对象的原型对象上。
Dancer.__proto__ === Human // true复制代码
的作用是使Human的静态方法(static method)继承到Dancer上。
_possibleConstructorReturn
_possibleConstructorReturn的作用这是将Dancer的this绑定到Human上并且执行:也就是这句: Object.getPrototypeOf(Dancer)).call(this, name),在这之前_inherits已经将Dancer.proto = Human,所以句的意思等于:Human.call(this, name),也就是Dancer的this会定义Human定义在构造的对象上的属性,也就是很多文章中说的:子类的constructor中的this是先被父类的constructor处理后返回的this作为子类的constructor的this再被定义子类的对应的属性
在看一个?:
class SuperMan extends Human { constructor(name, level) { super(name); this.level = level; } say() { console.info(`I am ${ this.name}, whose level is ${ this.level}`); } fly() { console.info(`${ this.name} is flying ~ so cool.`); }}var SuperMan = function (_Human2) { _inherits(SuperMan, _Human2); function SuperMan(name, level) { var _this2 = _possibleConstructorReturn(this, (SuperMan.__proto__ || Object.getPrototypeOf(SuperMan)).call(this, name)); _this2.level = level; return _this2; } _createClass(SuperMan, [{ key: 'say', value: function say() { console.info('I am ' + this.name + ', whose level is ' + this.level); } }, { key: 'fly', value: function fly() { console.info(this.name + ' is flying ~ so cool.'); } }]); return SuperMan;}(Human);复制代码
这里的_this2是被Human构造函数bind调用后的this,然后再定义了Dancer的level属性。
总结
基于上述的分析,Class & extends的语法糖本质上做了三件事:
class A {}class B extends A {}1 -> B.__proto__ === A // true2 -> B.prototype.__proto__ === A.prototype // true3 -> this(子类的constructor的this的处理)复制代码
参考资料: