ES5和ES6的繼承對比


ES5的繼承實現,這里以最佳實踐:寄生組合式繼承方式來實現。(為什么是最佳實踐,前面有隨筆講過了,可以參考)

function Super(name) {
  this.name = name;  
}

Super.prototype.sayName = function() {
   console.log(this.name)
}

function Sub(name, age) {
  Super.call(this, name);
  this.age = age;  
}

Sub.prototype.sayAge = function() {
    console.log(this.age)
}

Sub.prototype = Object.create(Super.prototype, {
    constructor: {
        value: Sub,
        writable: true,
        configurable: true
    }
});

這里的Object.create可以替換成Object.setPrototypeOf,好處是不用再手動綁定constructor的指向。

這是ES5繼承,再看下ES6的繼承,同樣實現上面的效果

class Super {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

class Sub extends Super {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
  sayAge() {
    console.log(this.age);
  }
}

 很明顯,ES6的繼承要更簡潔點,那區別是什么?

我們看一下babel解析后的ES6的繼承:

"use strict";

function _typeof(obj) {
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
            return typeof obj;
        };
    } else {
        _typeof = function _typeof(obj) {
            return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
    } return _typeof(obj);
}

function _possibleConstructorReturn(self, call) {
    if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
    } return _assertThisInitialized(self);
}

function _assertThisInitialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    } return self;
}

function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
    }; return _getPrototypeOf(o);
}

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            writable: true,
            configurable: true
        }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
}

function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _setPrototypeOf(o, p);
}

function _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}

function _classCallCheck(instance, Constructor) {
    if (!_instanceof(instance, Constructor)) {
        throw new TypeError("Cannot call a class as a 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);
    }
}

function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}

var Super =
    /*#__PURE__*/
    function () {
        function Super(name) {
            _classCallCheck(this, Super);

            this.name = name;
        }

        _createClass(Super, [{
            key: "sayName",
            value: function sayName() {
                console.log(this.name);
            }
        }]);

        return Super;
    }();

var Sub =
    /*#__PURE__*/
    function (_Super) {
        _inherits(Sub, _Super);

        function Sub(name, age) {
            var _this;

            _classCallCheck(this, Sub);

            _this = _possibleConstructorReturn(this, _getPrototypeOf(Sub).call(this, name));
            _this.age = age;
            return _this;
        }

        _createClass(Sub, [{
            key: "sayAge",
            value: function sayAge() {
                console.log(this.age);
            }
        }]);

        return Sub;
    }(Super);

 代碼有點多,但很多都是做了一些類型檢查或者是polify的兼容,關鍵的方法是兩個地方:

1,_inherits (這里等同於關鍵字extends的作用)

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            writable: true,
            configurable: true
        }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
}

前面的和ES5繼承沒有區別,也是用了Object.create實現子類的prototype繼承父類的prototype,但是最后多了一個操作

_setPrototypeOf(subClass, superClass);

 看一下對應的函數定義

function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _setPrototypeOf(o, p);
}

 意圖很明顯了,就是為了實現子類繼承父類!

從這里我們看出差別了,ES6的繼承除了子類的原型繼承以外,還多了子類的自身繼承父類,但是為什么這么做呢?

(這里筆者也沒有想明白為什么要這么做,歡迎留言補充解惑!)

 

 2,_possibleConstructorReturn (這里等同於super關鍵字)

function _possibleConstructorReturn(self, call) {
    if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
    } return _assertThisInitialized(self);
}

function _assertThisInitialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    } return self;
}

看一下用法

_this = _possibleConstructorReturn(this, _getPrototypeOf(Sub).call(this, name));

這里的 _getPrototypeOf(Sub) 實際上就是Super,因為上面使用了_inherits,所以已經繼承了類,因此這里就是等同於在Sub的內部使用了Super.call(this, name);從而實現了屬性的繼承,因此和ES5是一樣的。

 
        

 不過綜上來看,確實ES6的繼承要簡單很多,主要是寫法上比較簡單,不用手動去實現原型的繼承以及屬性的復制,但是本質上其實是一樣的。

 

end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM