ES6類以及繼承的實現原理

ES6中經過class關鍵字,定義類express

class Parent {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    speakSomething(){
        console.log("I can speek chinese");
    }
}

通過babel轉碼以後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.我以爲這樣的規範挺好的,可以規範化類的使用方式。this

轉碼中_createClass方法,它調用Object.defineProperty方法去給新建立的Parent添加各類屬性。defineProperties(Constructor.prototype, protoProps)是給原型添加屬性。若是你有靜態屬性,會直接添加到構造函數上defineProperties(Constructor, staticProps)。可是貌似並無用到,下面能夠證實.spa

這兩個流程走下來,其實就建立了一個類。prototype

上面講的是建立一個類的過程,那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()

轉碼以後的代碼變成了這樣code

"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核心方法來實現繼承,下面咱們就看下這個方法作了什麼?blog

首先是判斷父類的類型,而後繼承

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的靜態屬性,靜態方法了。

相關文章
相關標籤/搜索