class 繼承語法糖的本質(zhì)

https://www.cnblogs.com/annika/p/9073572.html
ES5和ES6中對于繼承的實現(xiàn)方法

ES6 的寫法:

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

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

轉(zhuǎn)成 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類繼承的本質(zhì):
class A extends B{}

1. A.__proto__ === B;  //繼承父類靜態(tài)屬性或方法。
2. A.prototype.__proto__ == B.prototype;//實例繼承鏈。
3. 子類的構(gòu)造函數(shù)中必定調(diào)用父類的構(gòu)造函數(shù)。
4. super作為對象時,在普通方法中,指向父類的原型對象( 即 B.prototype );在靜態(tài)方法中,指向父類( 即 B )。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容