es6实现继承详解
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实现继承详解的更多相关文章
- [原创]JavaScript继承详解
原文链接:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html 面向对象与基于对象 几乎每个开发人员都有面向对象语言(比如C++. ...
- “全栈2019”Java第九十九章:局部内部类与继承详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- 第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解
第8.3节 Python类的__init__方法深入剖析:构造方法与继承详解 一. 引言 上两节介绍了构造方法的语法及参数,说明了构造方法是Python的类创建实例后首先执行的方法,并说明如果类 ...
- 「万字图文」史上最姨母级Java继承详解
摘要:继承是面向对象软件技术中的一个概念.它使得复用以前的代码非常容易,能够大大缩短开发周期,降低开发费用. 本文分享自华为云社区<「万字图文」史上最姨母级Java继承详解丨[奔跑吧!JAVA] ...
- JavaScript ES6 新特性详解
JavaScript ES6 带来了新的语法和新的强大功能,使您的代码更现代,更易读 const , let and var 的区别: const , let 是 ES6 中用于声明变量的新关键字. ...
- es6入门4--promise详解
可以说每个前端开发者都无法避免解决异步问题,尤其是当处理了某个异步调用A后,又要紧接着处理其它逻辑,而最直观的做法就是通过回调函数(当然事件派发也可以)处理,比如: 请求A(function (请求响 ...
- CSS样式表继承详解
最近在恶补css样式表的基础知识.上次研究了css样式表之冲突问题详解 .这次是对 css 继承 特性的学习. 什么是css 继承?要想了解css样式表的继承,我们先从文档树(HTML DOM)开始. ...
- Kotlin——从无到有系列之中级篇(四):面向对象的特征与类(class)继承详解
如果您对Kotlin很有兴趣,或者很想学好这门语言,可以关注我的掘金,或者进入我的QQ群大家一起学习.进步. 欢迎各位大佬进群共同研究.探索 QQ群号:497071402 进入正题 在前面的章节中,详 ...
- JavaScript继承详解
面向对象与基于对象 在传统面向对象的语言中,有两个非常重要的概念 - 类和实例. 类定义了一类事物公共的行为和方法:而实例则是类的一个具体实现. 我们还知道,面向对象编程有三个重要的概念 - 封装.继 ...
随机推荐
- 判断手机浏览器还是微信浏览器(PHP)
//判断是否 微信浏览器 function isWeixin1() { if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== fa ...
- javascript 标签轮播
html <div id="banner-switch"> <!-- 切换内容 --> <div class="notice-content ...
- Ubuntu18.04安装jenkins
官网参考指引:https://pkg.jenkins.io/debian-stable/ wget -q -O - https://pkg.jenkins.io/debian-stable/jenki ...
- 解决samba和SELINUX 冲突
在使用Samba进行建立Window与Linux共享时,要是不能访问,出现"您可能没有权限使用网络资源", 那就是SELinux在作怪了 要是想让共享目录能访问,可以使用命令 #s ...
- RabbitMQ 3.9.7 镜像模式集群的搭建
1. 概述 老话说的好:做人脚踏实地,一步一个脚印,便定能战胜一切困难,最终取得成功!!! 言归正传,之前我们聊了 RabbitMQ 单点服务的安装,今天我们来聊聊 RabbitMQ 3.9.7 镜像 ...
- 带你读Paper丨分析ViT尚存问题和相对应的解决方案
摘要:针对ViT现状,分析ViT尚存问题和相对应的解决方案,和相关论文idea汇总. 本文分享自华为云社区<[ViT]目前Vision Transformer遇到的问题和克服方法的相关论文汇总& ...
- 设置 SSH 命令行空闲保持会话
楔子 使用 Mac 或 Linux 原生的命令行 ssh user@ip 方式连接 Linux 闲时会自动断开终端卡死. 为解决这个问题,查了到篇博客翻译下关键步骤记录下来.解决方式可以分服务端设置和 ...
- 题解 CF468C Hack it!
题目传送门 Description 设 \(f(i)\) 表示 \(i\) 的数码只和,给出 \(a\),求出 \(l,r\) 使得 \(\sum_{i=l}^{r} f(i)\equiv 0\pmo ...
- 洛谷2149 Elaxia的路线(dp+最短路)
QwQ好久没更新博客了,颓废了好久啊,来补一点东西 题目大意 给定两个点对,求两对点间最短路的最长公共路径. 其中\(n,m\le 10^5\) 比较简单吧 就是跑四遍最短路,然后把最短路上的边拿出来 ...
- OpenGL思维导图