美文网首页
class 继承语法糖的本质

class 继承语法糖的本质

作者: 苦苦修行 | 来源:发表于2019-12-19 13:57 被阅读0次

https://www.cnblogs.com/annika/p/9073572.html
ES5和ES6中对于继承的实现方法

ES6 的写法:

class A {
    name = 'name';
    hello(){
        console.log('A');
    }
}

class B extends A {
    age = 10;
    hello(){
        console.log('B');
    }
}

转成 ES5:

// 如何理解(this && this.__extends)?
// 如果 this 和 this.__extends 都为真,则返回最后一个真值;如果有一个不为真,则返回遇到的第一个不为真的值。
// 请见后面的示意图 1
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var A = /** @class */ (function () {
    function A() {
        this.name = 'name';
    }
    A.prototype.hello = function () {
        console.log('A');
    };
    return A;
}());
var B = /** @class */ (function (_super) {
    __extends(B, _super);
    function B() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.age = 10;
        return _this;
    }
    B.prototype.hello = function () {
        console.log('B');
    };
    return B;
}(A));

示意图 1:


截屏2019-09-1316.39.42.png ES5中的继承.png ES6中的继承.png
ES6类继承的本质:
class A extends B{}

1. A.__proto__ === B;  //继承父类静态属性或方法。
2. A.prototype.__proto__ == B.prototype;//实例继承链。
3. 子类的构造函数中必定调用父类的构造函数。
4. super作为对象时,在普通方法中,指向父类的原型对象( 即 B.prototype );在静态方法中,指向父类( 即 B )。

相关文章

  • class 继承语法糖的本质

    https://www.cnblogs.com/annika/p/9073572.htmlES5和ES6中对于继承...

  • 2019-06-18 JS 中继承的写法

    使用 prototype 如何继承 使用 class 语法糖如何继承 ``` class Human{ ...

  • 13.JS基础之class的构建与继承

    class为es6推出的,本质上就是原型链继承的语法糖,例如有class People ,typeof Peopl...

  • [JavaScript] class

    ES6中的class基于原型继承创建类。 (1)class只是原型继承的语法糖 相当于: 注: class定义中...

  • 详解ES6中的class

    文章首发于 个人博客 目录 class 静态方法 静态属性 继承 super class class是一个语法糖,...

  • 理解JavaScript的原型与继承

    Javascript 使用原型来实现类的继承。在ECMAScript6 引入class的概念也是原型继承的语法糖...

  • ES6 中 class 与构造函数的关系

    ES6 中 class 与构造函数的关系class 为 构造函数的语法糖,即 class 的本质是 构造函数。c...

  • class-继承(es6)

    继承-JS 继承-class class-总结 Class 在语法上更加贴合面向对象的写法Class 实现继承更加...

  • js继承 es6和es5

    es6 class是个语法糖,本质上是原型链 es6之前

  • ES6

    ES6是一个语言标准,不是一个框架。 ES6中的class与继承 class是创建类对象与实现类继承的语法糖,旨在...

网友评论

      本文标题:class 继承语法糖的本质

      本文链接:https://www.haomeiwen.com/subject/sknnyctx.html