ES6 -> Javascript的类与继承在Babel的实现

栏目: JavaScript · 发布时间: 5年前

内容简介:闲来无事,看了下babel对于Javascript ES6中的类与继承的实现,整理一下。:cow::hamster::panda_face:大家都知道ES6的Class是语法糖,Javascript本身是没有类的概念的,要实现继承的概念可以使用原型链的方式。既然是语法糖,那就看看babel编译成ES5的代码就可以了。举个:chestnut::

闲来无事,看了下babel对于Javascript ES6中的类与继承的实现,整理一下。:cow::hamster::panda_face:

大家都知道ES6的Class是语法糖,Javascript本身是没有类的概念的,要实现继承的概念可以使用原型链的方式。既然是语法糖,那就看看babel编译成ES5的代码就可以了。

举个:chestnut::

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();
复制代码

上述执行结果如下:

ES6 -> Javascript的类与继承在Babel的实现

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本质上是一个构造函数,:chestnut:中就是Human函数,其中在Class的constructor中通过this.name定义的属性name是之后在构造的对象【这里我们成为instance,方便之后说明】上的属性,被编译成熟悉的:

function Human(name) {
    this.name = name;
  }
复制代码

在:chestnut:中,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**两个新出现的方法:

ES6 -> Javascript的类与继承在Babel的实现

_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再被定义子类的对应的属性

在看一个:chestnut::

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 // true

2 -> B.prototype.__proto__ === A.prototype // true
3 -> this(子类的constructor的this的处理)
复制代码

参考资料:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SSA:用户搜索心理与行为分析

SSA:用户搜索心理与行为分析

[美] 罗森菲尔德(Louis Rosenfeld) / 汤海、蔡复青 / 清华大学出版社 / 2014-4-1 / 59.00

何为站内搜索分析(SSA)?它如何帮助你挖掘用户搜索曰志,从中洞悉用户搜索心理和行为,从而有针对性地改善用户体验,提升网站价值?这些都可以从《SSA:用户搜索心理与行为分析》中找到答案。《SSA:用户搜索心理与行为分析》首先通过故事来说明SSA是如何使Vanguard集团起死回生的,简要介绍SSA并指导读者动手实践。其次,通过丰富的实例来介绍很多工具和方法,帮助读者着手分析用户查询数据,从中获得更......一起来看看 《SSA:用户搜索心理与行为分析》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具