详解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 相关文章推荐
JCalendar 日历控件 v1.0 beta[兼容IE&amp;Firefox] 有文档和例子
May 30 Javascript
高效率JavaScript编写技巧整理
Aug 23 Javascript
JQUERY dialog的用法详细解析
Dec 19 Javascript
JS打开新窗口防止被浏览器阻止的方法
Jan 03 Javascript
简介alert()与console.log()的不同
Aug 26 Javascript
jquery验证手机号是否正确实例讲解
Nov 17 Javascript
利用jquery制作滚动到指定位置触发动画
Mar 26 Javascript
javascript入门之数组[新手必看]
Nov 21 Javascript
bootstrap multiselect下拉列表功能
Aug 22 Javascript
动态统计当前输入内容的字节、字符数的实例详解
Oct 27 Javascript
js canvas实现橡皮擦效果
Dec 20 Javascript
详解vue3.0 diff算法的使用(超详细)
Jul 01 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 echo()函数讲解
2019/02/15 PHP
Aster vs Newbee BO5 第二场2.19
2021/03/10 DOTA
THREE.JS入门教程(1)THREE.JS使用前了解
2013/01/24 Javascript
js动态创建表格,删除行列的小例子
2013/07/20 Javascript
JS创建对象的写法示例
2016/11/04 Javascript
bootstrap suggest下拉框使用详解
2017/04/10 Javascript
jquery.rotate.js实现可选抽奖次数和中奖内容的转盘抽奖代码
2017/08/23 jQuery
JS实现手写parseInt的方法示例
2017/09/24 Javascript
pm2 部署 node的三种方法示例
2017/10/20 Javascript
node简单实现一个更改头像功能的示例
2017/12/29 Javascript
浅谈Node.js 中间件模式
2018/06/12 Javascript
vue-cli初始化项目中使用less的方法
2018/08/09 Javascript
JS中验证整数和小数的正则表达式
2018/10/08 Javascript
如何自动化部署项目?折腾服务器之旅~
2019/04/16 Javascript
python通过urllib2获取带有中文参数url内容的方法
2015/03/13 Python
python实现读取命令行参数的方法
2015/05/22 Python
python+matplotlib实现礼盒柱状图实例代码
2018/01/16 Python
Python 对输入的数字进行排序的方法
2018/06/23 Python
python lambda函数及三个常用的高阶函数
2020/02/05 Python
动态设置django的model field的默认值操作步骤
2020/03/30 Python
印度尼西亚电子产品购物网站:Kliknklik
2018/06/05 全球购物
德国健康生活方式网上商店:Landkaufhaus Mayer
2019/03/12 全球购物
eharmony澳大利亚:网上约会服务
2020/02/29 全球购物
公务员培训自我鉴定
2013/09/19 职场文书
信息系统专业个人求职信范文
2013/12/07 职场文书
总经理司机职责
2014/02/02 职场文书
城管综合整治方案
2014/05/01 职场文书
安全口号大全
2014/06/21 职场文书
2015社区爱国卫生工作总结
2015/04/21 职场文书
2015年维修工作总结
2015/04/25 职场文书
MySQL优化之如何写出高质量sql语句
2021/05/17 MySQL
Python re.sub 反向引用的实现
2021/07/07 Python
Vue如何清空对象
2022/03/03 Vue.js
redis sentinel监控高可用集群实现的配置步骤
2022/04/01 Redis
Nginx 配置 HTTPS的详细过程
2022/05/30 Servers
Python实现信息管理系统
2022/06/05 Python