成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

ES6 系列之 Babel 是如何編譯 Class 的(下)

endiat / 488人閱讀

摘要:以上的代碼對應(yīng)到就是調(diào)用父類的值得注意的是關(guān)鍵字表示父類的構(gòu)造函數(shù),相當(dāng)于的。舉個例子這是因為作為構(gòu)造函數(shù)的語法糖,同時有屬性和屬性,因此同時存在兩條繼承鏈。子類的屬性,表示構(gòu)造函數(shù)的繼承,總是指向父類。

前言

在上一篇 《 ES6 系列 Babel 是如何編譯 Class 的(上)》,我們知道了 Babel 是如何編譯 Class 的,這篇我們學(xué)習(xí) Babel 是如何用 ES5 實現(xiàn) Class 的繼承。

ES5 寄生組合式繼承
function Parent (name) {
    this.name = name;
}

Parent.prototype.getName = function () {
    console.log(this.name)
}

function Child (name, age) {
    Parent.call(this, name);
    this.age = age;
}

Child.prototype = Object.create(Parent.prototype);

var child1 = new Child("kevin", "18");

console.log(child1);

原型鏈?zhǔn)疽鈭D為:

關(guān)于寄生組合式繼承我們在 《JavaScript深入之繼承的多種方式和優(yōu)缺點》 中介紹過。

引用《JavaScript高級程序設(shè)計》中對寄生組合式繼承的夸贊就是:

這種方式的高效率體現(xiàn)它只調(diào)用了一次 Parent 構(gòu)造函數(shù),并且因此避免了在 Parent.prototype 上面創(chuàng)建不必要的、多余的屬性。與此同時,原型鏈還能保持不變;因此,還能夠正常使用 instanceof 和 isPrototypeOf。開發(fā)人員普遍認(rèn)為寄生組合式繼承是引用類型最理想的繼承范式。
ES6 extend

Class 通過 extends 關(guān)鍵字實現(xiàn)繼承,這比 ES5 的通過修改原型鏈實現(xiàn)繼承,要清晰和方便很多。

以上 ES5 的代碼對應(yīng)到 ES6 就是:

class Parent {
    constructor(name) {
        this.name = name;
    }
}

class Child extends Parent {
    constructor(name, age) {
        super(name); // 調(diào)用父類的 constructor(name)
        this.age = age;
    }
}

var child1 = new Child("kevin", "18");

console.log(child1);

值得注意的是:

super 關(guān)鍵字表示父類的構(gòu)造函數(shù),相當(dāng)于 ES5 的 Parent.call(this)。

子類必須在 constructor 方法中調(diào)用 super 方法,否則新建實例時會報錯。這是因為子類沒有自己的 this 對象,而是繼承父類的 this 對象,然后對其進行加工。如果不調(diào)用 super 方法,子類就得不到 this 對象。

也正是因為這個原因,在子類的構(gòu)造函數(shù)中,只有調(diào)用 super 之后,才可以使用 this 關(guān)鍵字,否則會報錯。

子類的 __proto__

在 ES6 中,父類的靜態(tài)方法,可以被子類繼承。舉個例子:

class Foo {
  static classMethod() {
    return "hello";
  }
}

class Bar extends Foo {
}

Bar.classMethod(); // "hello"

這是因為 Class 作為構(gòu)造函數(shù)的語法糖,同時有 prototype 屬性和 __proto__ 屬性,因此同時存在兩條繼承鏈。

(1)子類的 __proto__ 屬性,表示構(gòu)造函數(shù)的繼承,總是指向父類。

(2)子類 prototype 屬性的 __proto__ 屬性,表示方法的繼承,總是指向父類的 prototype 屬性。

class Parent {
}

class Child extends Parent {
}

console.log(Child.__proto__ === Parent); // true
console.log(Child.prototype.__proto__ === Parent.prototype); // true

ES6 的原型鏈?zhǔn)疽鈭D為:

我們會發(fā)現(xiàn),相比寄生組合式繼承,ES6 的 class 多了一個 Object.setPrototypeOf(Child, Parent) 的步驟。

繼承目標(biāo)

extends 關(guān)鍵字后面可以跟多種類型的值。

class B extends A {
}

上面代碼的 A,只要是一個有 prototype 屬性的函數(shù),就能被 B 繼承。由于函數(shù)都有 prototype 屬性(除了 Function.prototype 函數(shù)),因此 A 可以是任意函數(shù)。

除了函數(shù)之外,A 的值還可以是 null,當(dāng) extend null 的時候:

class A extends null {
}

console.log(A.__proto__ === Function.prototype); // true
console.log(A.prototype.__proto__ === undefined); // true
Babel 編譯

那 ES6 的這段代碼:

class Parent {
    constructor(name) {
        this.name = name;
    }
}

class Child extends Parent {
    constructor(name, age) {
        super(name); // 調(diào)用父類的 constructor(name)
        this.age = age;
    }
}

var child1 = new Child("kevin", "18");

console.log(child1);

Babel 又是如何編譯的呢?我們可以在 Babel 官網(wǎng)的 Try it out 中嘗試:

"use strict";

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 Parent(name) {
    _classCallCheck(this, Parent);

    this.name = name;
};

var Child = function(_Parent) {
    _inherits(Child, _Parent);

    function Child(name, age) {
        _classCallCheck(this, Child);

        // 調(diào)用父類的 constructor(name)
        var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, name));

        _this.age = age;
        return _this;
    }

    return Child;
}(Parent);

var child1 = new Child("kevin", "18");

console.log(child1);

我們可以看到 Babel 創(chuàng)建了 _inherits 函數(shù)幫助實現(xiàn)繼承,又創(chuàng)建了 _possibleConstructorReturn 函數(shù)幫助確定調(diào)用父類構(gòu)造函數(shù)的返回值,我們來細致的看一看代碼。

_inherits
function _inherits(subClass, superClass) {
    // extend 的繼承目標(biāo)必須是函數(shù)或者是 null
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }

    // 類似于 ES5 的寄生組合式繼承,使用 Object.create,設(shè)置子類 prototype 屬性的 __proto__ 屬性指向父類的 prototype 屬性
    subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });

    // 設(shè)置子類的 __proto__ 屬性指向父類
    if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

關(guān)于 Object.create(),一般我們用的時候會傳入一個參數(shù),其實是支持傳入兩個參數(shù)的,第二個參數(shù)表示要添加到新創(chuàng)建對象的屬性,注意這里是給新創(chuàng)建的對象即返回值添加屬性,而不是在新創(chuàng)建對象的原型對象上添加。

舉個例子:

// 創(chuàng)建一個以另一個空對象為原型,且擁有一個屬性 p 的對象
const o = Object.create({}, { p: { value: 42 } });
console.log(o); // {p: 42}
console.log(o.p); // 42

再完整一點:

const o = Object.create({}, {
    p: {
        value: 42,
        enumerable: false,
        // 該屬性不可寫
        writable: false,
        configurable: true
    }
});
o.p = 24;
console.log(o.p); // 42

那么對于這段代碼:

subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });

作用就是給 subClass.prototype 添加一個可配置可寫不可枚舉的 constructor 屬性,該屬性值為 subClass。

_possibleConstructorReturn

函數(shù)里是這樣調(diào)用的:

var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, name));

我們簡化為:

var _this = _possibleConstructorReturn(this, Parent.call(this, name));

_possibleConstructorReturn 的源碼為:

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;
}

在這里我們判斷 Parent.call(this, name) 的返回值的類型,咦?這個值還能有很多類型?

對于這樣一個 class:

class Parent {
    constructor() {
        this.xxx = xxx;
    }
}

Parent.call(this, name) 的值肯定是 undefined??墒侨绻覀冊?constructor 函數(shù)中 return 了呢?比如:

class Parent {
    constructor() {
        return {
            name: "kevin"
        }
    }
}

我們可以返回各種類型的值,甚至是 null:

class Parent {
    constructor() {
        return null
    }
}

我們接著看這個判斷:

call && (typeof call === "object" || typeof call === "function") ? call : self;

注意,這句話的意思并不是判斷 call 是否存在,如果存在,就執(zhí)行 (typeof call === "object" || typeof call === "function") ? call : self

因為 && 的運算符優(yōu)先級高于 ? :,所以這句話的意思應(yīng)該是:

(call && (typeof call === "object" || typeof call === "function")) ? call : self;

對于 Parent.call(this) 的值,如果是 object 類型或者是 function 類型,就返回 Parent.call(this),如果是 null 或者基本類型的值或者是 undefined,都會返回 self 也就是子類的 this。

這也是為什么這個函數(shù)被命名為 _possibleConstructorReturn。

總結(jié)
var Child = function(_Parent) {
    _inherits(Child, _Parent);

    function Child(name, age) {
        _classCallCheck(this, Child);

        // 調(diào)用父類的 constructor(name)
        var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, name));

        _this.age = age;
        return _this;
    }

    return Child;
}(Parent);

最后我們總體看下如何實現(xiàn)繼承:

首先執(zhí)行 _inherits(Child, Parent),建立 Child 和 Parent 的原型鏈關(guān)系,即 Object.setPrototypeOf(Child.prototype, Parent.prototype)Object.setPrototypeOf(Child, Parent)

然后調(diào)用 Parent.call(this, name),根據(jù) Parent 構(gòu)造函數(shù)的返回值類型確定子類構(gòu)造函數(shù) this 的初始值 _this。

最終,根據(jù)子類構(gòu)造函數(shù),修改 _this 的值,然后返回該值。

ES6 系列

ES6 系列目錄地址:https://github.com/mqyqingfeng/Blog

ES6 系列預(yù)計寫二十篇左右,旨在加深 ES6 部分知識點的理解,重點講解塊級作用域、標(biāo)簽?zāi)0?、箭頭函數(shù)、Symbol、Set、Map 以及 Promise 的模擬實現(xiàn)、模塊加載方案、異步處理等內(nèi)容。

如果有錯誤或者不嚴(yán)謹(jǐn)?shù)牡胤?,請?wù)必給予指正,十分感謝。如果喜歡或者有所啟發(fā),歡迎 star,對作者也是一種鼓勵。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/99068.html

相關(guān)文章

  • ES6 系列 Babel 如何編譯 Class (上)

    摘要:前言在了解是如何編譯前,我們先看看的和的構(gòu)造函數(shù)是如何對應(yīng)的。這是它跟普通構(gòu)造函數(shù)的一個主要區(qū)別,后者不用也可以執(zhí)行。該函數(shù)的作用就是將函數(shù)數(shù)組中的方法添加到構(gòu)造函數(shù)或者構(gòu)造函數(shù)的原型中,最后返回這個構(gòu)造函數(shù)。 前言 在了解 Babel 是如何編譯 class 前,我們先看看 ES6 的 class 和 ES5 的構(gòu)造函數(shù)是如何對應(yīng)的。畢竟,ES6 的 class 可以看作一個語法糖,...

    shadajin 評論0 收藏0
  • 揭秘babel魔法class魔法處理

    摘要:年,很多人已經(jīng)開始接觸環(huán)境,并且早已經(jīng)用在了生產(chǎn)當(dāng)中。我們發(fā)現(xiàn),關(guān)鍵字會被編譯成構(gòu)造函數(shù),于是我們便可以通過來實現(xiàn)實例的生成。下一篇文章我會繼續(xù)介紹如何處理子類的并會通過一段函數(shù)橋梁,使得環(huán)境下也能夠繼承定義的。 2017年,很多人已經(jīng)開始接觸ES6環(huán)境,并且早已經(jīng)用在了生產(chǎn)當(dāng)中。我們知道ES6在大部分瀏覽器還是跑不通的,因此我們使用了偉大的Babel來進行編譯。很多人可能沒有關(guān)心過,...

    wqj97 評論0 收藏0
  • 揭秘babel魔法class繼承處理2

    摘要:并且用驗證了中一系列的實質(zhì)就是魔法糖的本質(zhì)。抽絲剝繭我們首先看的編譯結(jié)果這是一個自執(zhí)行函數(shù),它接受一個參數(shù)就是他要繼承的父類,返回一個構(gòu)造函數(shù)。 如果你已經(jīng)看過第一篇揭秘babel的魔法之class魔法處理,這篇將會是一個延伸;如果你還沒看過,并且也不想現(xiàn)在就去讀一下,單獨看這篇也沒有關(guān)系,并不存在理解上的障礙。 上一篇針對Babel對ES6里面基礎(chǔ)class的編譯進行了分析。這一篇將...

    BlackHole1 評論0 收藏0
  • ES6 系列我們來聊聊裝飾器

    摘要:第二部分源碼解析接下是應(yīng)用多個第二部分對于一個方法應(yīng)用了多個,比如會編譯為在第二部分的源碼中,執(zhí)行了和操作,由此我們也可以發(fā)現(xiàn),如果同一個方法有多個裝飾器,會由內(nèi)向外執(zhí)行。有了裝飾器,就可以改寫上面的代碼。 Decorator 裝飾器主要用于: 裝飾類 裝飾方法或?qū)傩? 裝飾類 @annotation class MyClass { } function annotation(ta...

    eternalshallow 評論0 收藏0

發(fā)表評論

0條評論

endiat

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<