详解ES6中class的实现原理


Posted in Javascript onOctober 03, 2020

一、在ES6以前实现类和继承

实现类的代码如下:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.speakSomething = function () {
  console.log("I can speek chinese");
};

实现继承的代码如下:一般使用原型链继承和call继承混合的形式

function Person(name) {
  this.name = name;
}

Person.prototype.showName = function () {
  return `名字是:${this.name}`;
};

function Student(name, skill) {
  Person.call(this, name);//继承属性
  this.skill = skill;
}

Student.prototype = new Person();//继承方法

二、ES6使用class定义类

class Parent {
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  speakSomething(){
    console.log("I can speek chinese");
  }
}

经过babel转码之后

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var Parent = function () {
  function Parent(name, age) {
    _classCallCheck(this, Parent);

    this.name = name;
    this.age = age;
  }

  _createClass(Parent, [{
    key: "speakSomething",
    value: function speakSomething() {
      console.log("I can speek chinese");
    }
  }]);

  return Parent;
}();

可以看到ES6类的底层还是通过构造函数去创建的。

通过ES6创建的类,是不允许你直接调用的。在ES5中,构造函数是可以直接运行的,比如Parent()。但是在ES6就不行。我们可以看到转码的构造函数中有_classCallCheck(this, Parent)语句,这句话是防止你通过构造函数直接运行的。你直接在ES6运行Parent(),这是不允许的,ES6中抛出Class constructor Parent cannot be invoked without 'new'错误。转码后的会抛出Cannot call a class as a function.能够规范化类的使用方式。

转码中_createClass方法,它调用Object.defineProperty方法去给新创建的Parent添加各种属性。defineProperties(Constructor.prototype, protoProps)是给原型添加属性。如果你有静态属性,会直接添加到构造函数defineProperties(Constructor, staticProps)上。

三、ES6实现继承

我们给Parent添加静态属性,原型属性,内部属性。

class Parent {
  static height = 12
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  speakSomething(){
    console.log("I can speek chinese");
  }
}
Parent.prototype.color = 'yellow'


//定义子类,继承父类
class Child extends Parent {
  static width = 18
  constructor(name,age){
    super(name,age);
  }
  coding(){
    console.log("I can code JS");
  }
}

经过babel转码之后

"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;
  };
}();
 
function _possibleConstructorReturn(self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
 
function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
 
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
 
var Parent = function () {
  function Parent(name, age) {
    _classCallCheck(this, Parent);
 
    this.name = name;
    this.age = age;
  }
 
  _createClass(Parent, [{
    key: "speakSomething",
    value: function speakSomething() {
      console.log("I can speek chinese");
    }
  }]);
 
  return Parent;
}();
 
Parent.height = 12;
 
Parent.prototype.color = 'yellow';
 
//定义子类,继承父类
 
var Child = function (_Parent) {
  _inherits(Child, _Parent);
 
  function Child(name, age) {
    _classCallCheck(this, Child);
 
    return _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, name, age));
  }
 
  _createClass(Child, [{
    key: "coding",
    value: function coding() {
      console.log("I can code JS");
    }
  }]);
 
  return Child;
}(Parent);
 
Child.width = 18;

构造类的方法都没变,只是添加了_inherits核心方法来实现继承。具体步骤如下:

首先是判断父类的类型,然后:

subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });

这段代码翻译下来就是

function F(){}
F.prototype = superClass.prototype
subClass.prototype = new F()
subClass.prototype.constructor = subClass

接下来就是subClass.__proto__ = superClass

_inherits核心思想就是下面两句: 

subClass.prototype.__proto__ = superClass.prototype
subClass.__proto__ = superClass

如下图所示:

详解ES6中class的实现原理

首先 subClass.prototype.__proto__ = superClass.prototype保证了子类的实例instanceof父类是true,子类的实例可以访问到父类的属性,包括内部属性,以及原型属性。

其次,subClass.__proto__ = superClass,保证了静态属性也能访问到,也就是这个例子中的Child.height。

以上就是详解ES6中class的实现原理的详细内容,更多关于ES6中class的实现原理的资料请关注三水点靠木其它相关文章!

Javascript 相关文章推荐
js电信网通双线自动选择技巧
Nov 18 Javascript
js一组验证函数
Dec 20 Javascript
Javascript String对象扩展HTML编码和解码的方法
Jun 02 Javascript
通过$(this)使用jQuery包装后的方法或属性
May 18 Javascript
js运动应用实例解析
Dec 28 Javascript
jQuery+CSS3+Html5实现弹出层效果实例代码(附源码下载)
May 16 Javascript
JavaScript实现的select点菜功能示例
Jan 16 Javascript
JS+HTML实现的圆形可点击区域示例【3种方法】
Aug 01 Javascript
分享5个顶级的JavaScript Ajax组件库
Sep 16 Javascript
Vue监听页面刷新和关闭功能
Jun 20 Javascript
如何在JavaScript中等分数组的实现
Dec 13 Javascript
Ajax 的初步实现(使用vscode+node.js+express框架)
Jun 18 Javascript
在vue中使用Echarts画曲线图的示例
Oct 03 #Javascript
vue 虚拟DOM的原理
Oct 03 #Javascript
vue使用video插件vue-video-player的示例
Oct 03 #Javascript
区分vue-router的hash和history模式
Oct 03 #Javascript
Vue双向数据绑定(MVVM)的原理
Oct 03 #Javascript
Chrome插件开发系列一:弹窗终结者开发实战
Oct 02 #Javascript
js通过canvas生成图片缩略图
Oct 02 #Javascript
You might like
php+mysqli事务控制实现银行转账实例
2015/01/29 PHP
PHP中通过getopt解析GNU C风格命令行选项
2019/11/18 PHP
基于JQuery的简单实现折叠菜单代码
2010/09/15 Javascript
javascript 小数取整简单实现方式
2014/05/30 Javascript
jQuery Validation Plugin验证插件手动验证
2016/01/26 Javascript
JS使用cookie设置样式的方法
2016/06/30 Javascript
有关JS中的0,null,undefined,[],{},'''''''',false之间的关系
2017/02/14 Javascript
从零学习node.js之搭建http服务器(二)
2017/02/21 Javascript
jQuery动态移除和添加背景图片的方法详解
2017/03/07 Javascript
jQuery选择器之表单元素选择器详解
2017/09/19 jQuery
20个最常见的jQuery面试问题及答案
2018/05/23 jQuery
基于vue实现一个神奇的动态按钮效果
2019/05/15 Javascript
微信小程序调用后台service教程详解
2020/11/06 Javascript
Python自动化运维和部署项目工具Fabric使用实例
2016/09/18 Python
django admin添加数据自动记录user到表中的实现方法
2018/01/05 Python
Python实现七彩蟒蛇绘制实例代码
2018/01/16 Python
Python实现账号密码输错三次即锁定功能简单示例
2019/03/29 Python
python实现的批量分析xml标签中各个类别个数功能示例
2019/12/30 Python
python opencv实现信用卡的数字识别
2020/01/12 Python
python字符串替换re.sub()实例解析
2020/02/09 Python
python 实现单例模式的5种方法
2020/09/23 Python
CSS3改变浏览器滚动条样式
2019/01/04 HTML / CSS
廉价连衣裙和婚纱礼服在线销售:Tbdress
2019/02/28 全球购物
职工运动会邀请函
2014/01/19 职场文书
小松树教学反思
2014/02/11 职场文书
计算机专业毕业生自荐信范文
2014/03/06 职场文书
单位工作证明
2014/10/07 职场文书
2014最新党员违纪检讨书
2014/10/12 职场文书
2014年煤矿工作总结
2014/11/24 职场文书
2016大学生党校学习心得体会
2016/01/06 职场文书
《圆明园的毁灭》教学反思
2016/02/16 职场文书
nginx基于域名,端口,不同IP的虚拟主机设置的实现
2021/03/31 Servers
排查并解决MySQL生产库内存使用率高的报警
2022/04/11 MySQL
Win11 KB5015814遇安装失败 影响开始菜单性能解决方法
2022/07/15 数码科技
基于Android10渲染Surface的创建过程
2022/08/14 Java/Android
MySQL使用IF语句及用case语句对条件并结果进行判断 
2022/09/23 MySQL