class 继承语法糖的本质

2019-12-19  本文已影响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 )。
上一篇 下一篇

猜你喜欢

热点阅读