ES6中通过class关键字,定义类

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

经过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 _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");
}
} var c = new Child("job",30);
c.coding()

转码之后的代码变成了这样

"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; var c = new Child("job", 30);
c.coding();

我们可以看到,构造类的方法都没变,只是添加了_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

一图胜千言

那为什么这样一倒腾,它就实现了继承了呢?
首先 subClass.prototype.__proto__ = superClass.prototype保证了c instanceof Parent是true,Child的实例可以访问到父类的属性,包括内部属性,以及原型属性。其次,subClass.__proto__ = superClass,保证了Child.height也能访问到,也就是静态方法。

subClass.__proto__ = superClass不是很好理解,可以通过下面的方式理解

function A(){}
var a = new A()
a.__proto__ = A.prototype

a是一个实例,A.prototype是构造方法的原型。通过这种方式,那么a就可以访问A.prototype上面的方法。

那把 subClass类比成 a,superClass类比成A.prototype,那是不是subClass可以直接访问 superClass的静态属性,静态方法了。

es6实现继承详解的更多相关文章

  1. [原创]JavaScript继承详解

    原文链接:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html 面向对象与基于对象 几乎每个开发人员都有面向对象语言(比如C++. ...

  2. “全栈2019”Java第九十九章:局部内部类与继承详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  3. 第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解

    第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解 一.    引言 上两节介绍了构造方法的语法及参数,说明了构造方法是Python的类创建实例后首先执行的方法,并说明如果类 ...

  4. 「万字图文」史上最姨母级Java继承详解

    摘要:继承是面向对象软件技术中的一个概念.它使得复用以前的代码非常容易,能够大大缩短开发周期,降低开发费用. 本文分享自华为云社区<「万字图文」史上最姨母级Java继承详解丨[奔跑吧!JAVA] ...

  5. JavaScript ES6 新特性详解

    JavaScript ES6 带来了新的语法和新的强大功能,使您的代码更现代,更易读 const ,  let and var 的区别: const , let 是 ES6 中用于声明变量的新关键字. ...

  6. es6入门4--promise详解

    可以说每个前端开发者都无法避免解决异步问题,尤其是当处理了某个异步调用A后,又要紧接着处理其它逻辑,而最直观的做法就是通过回调函数(当然事件派发也可以)处理,比如: 请求A(function (请求响 ...

  7. CSS样式表继承详解

    最近在恶补css样式表的基础知识.上次研究了css样式表之冲突问题详解 .这次是对 css 继承 特性的学习. 什么是css 继承?要想了解css样式表的继承,我们先从文档树(HTML DOM)开始. ...

  8. Kotlin——从无到有系列之中级篇(四):面向对象的特征与类(class)继承详解

    如果您对Kotlin很有兴趣,或者很想学好这门语言,可以关注我的掘金,或者进入我的QQ群大家一起学习.进步. 欢迎各位大佬进群共同研究.探索 QQ群号:497071402 进入正题 在前面的章节中,详 ...

  9. JavaScript继承详解

    面向对象与基于对象 在传统面向对象的语言中,有两个非常重要的概念 - 类和实例. 类定义了一类事物公共的行为和方法:而实例则是类的一个具体实现. 我们还知道,面向对象编程有三个重要的概念 - 封装.继 ...

随机推荐

  1. 【小程序】微信小程序iOS苹果报错“协议错误”

    遇到问题 目前正在开发一个小程序,然后苹果真机测试时发现无法授权并提示,errMsg:"request:fail 未能完成该操作.协议错误" 开发环境下测试没问题,安卓机真机测试没 ...

  2. layui 利用js原型方法来加载函数

    //举例如下: !function (win) { var FUNC = function () { this.v = "3.3" }; //这里添加函数 FUNC.prototy ...

  3. 『GoLang』fmt包的使用

    目录 1. fmt 包初识 2. 格式化 verb 应用 2.1 通用 2.2 布尔值 2.3 整数 2.4 浮点数与复数 2.5 字符串和 []byte 2.6 指针 2.7 其他 flag 2.8 ...

  4. CF803G-Periodic RMQ Problem【离散化,线段树,ST表】

    正题 题目链接:https://www.luogu.com.cn/problem/CF803G 题目大意 一个长度为\(n\)的序列\(a\)复制\(k\)份连接,要求支持 区间赋值 区间查询最小值 ...

  5. Markdown 相关语法

    MD语法博客:https://www.cnblogs.com/Jetictors/p/8506757.html 公式 \[\mathbf{x}_{t}=\Phi_{t}\left(\mathbf{x} ...

  6. 【C++ Primer Plus】编程练习答案——第10章

    1 // chapter10_1_account.h 2 3 #ifndef LEARN_CPP_CHAPTER10_1_ACCOUNT_H 4 #define LEARN_CPP_CHAPTER10 ...

  7. Vulnhub实战-JIS-CTF_VulnUpload靶机👻

    Vulnhub实战-JIS-CTF_VulnUpload靶机 下载地址:http://www.vulnhub.com/entry/jis-ctf-vulnupload,228/ 你可以从上面地址获取靶 ...

  8. 11.4.3 LVS-TUN

    LVS-TUN 用IP隧道技术实现虚拟服务器。这种方式是在集群的节点不在同一个网段时可用的转发机制,是将IP包封装在其他网络流量中的方法。为了安全的考虑,应该使用隧道技术中的VPN,也可使用租用专线。 ...

  9. C++核心编程 2 引用

    引用的基本使用 作用:给变量起别名 ,语法:数据类型 & 别名 = 原名 注意:引用必须初始化,且初始化之后,就不可更改. 引用做函数参数 作用:函数传参时,可以利用引用的技术让形参修饰实参 ...

  10. xml文件报Element 'beans' cannot have character [children],because the type's content type is element

    写springMvc.xml文件时,偶然遇到 Element 'beans' cannot have character [children],because the type's content t ...