• 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

  • 相关阅读:
    dategrid快速录入一行数据的一波操作
    shiro权限控制入门
    Activiti工作流小序曲
    在线HTML文档编辑器使用入门之图片上传与图片管理的实现
    ActiveMQ整合spring结合项目开发流程(生产者和消费者)总结
    缓存框架EhCache的简单使用
    关于特征工程入门中的一些基本知识
    SQL SERVER常用系统表和常用函数
    TestOne
    JS 代码调试经验总结
  • 原文地址:https://www.cnblogs.com/yanchenyu/p/11459334.html
Copyright © 2020-2023  润新知