ES2015继承的实现

# ES2015继承
class A {
    ma = 'ma';
    static sa = 'sa';
    static sf = () => {
        return 'sf';
    }
}
class B extends A {
}

let b = new B();

以上代码经过Babel编译后为


// 1. 删除检查代码
// 2. 仅使用Object.setProtypeOf和Object.getPrototypeOf设置和访问对象内部[[Prototype]]
function _inherits(subClass, superClass) {
    
    // 设置原型对象,实现原型继承
    subClass.prototype = Object.create(superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    // 实现静态属性继承
    // subClass.sa === superClass.sa;
    Object.setPrototypeOf(subClass, superClass);
}

var A = function A() {
    this.ma = 'ma';
};

A.sa = 'sa';
A.sf = function() {
    return 'sf';
};

var B = function(_A) {
    // B.prototype = _A.prototype;
    // Object.setPrototypeOf(B, A);
    _inherits(B, _A);
    
    function B() {
        // 初始化父类实例属性
        // _A.apply(this, arguments);
        return Object.getPrototypeOf(B).apply(this, arguments);  
    }
    return B;
} (A);

let b = new B();

以上代码主要做了三件事

  • 通过B.prototype设置构造函数的原型链,实现原型继承
  • 通过Object.setPrototypeOf设置函数对象的的内部原型属性,实现静态属性继承
  • 通过apply,将this和arguments应用到父类构造函数,初始化父类实例属性

Javascript静态变量继承的特点

let same = B.sa === A.sa;   // true
let has = B.hasOwnProterty('sa'); // false

PS:
react-redux的connect方法,内部通过判断hasOwnProperty来复制静态变量,所以在出现组件继承时会有如下结果

class SuperComponent extends React.Component {  
    static mSup= {...}
    ...
}
class SubComponent extends SuperComponent { 
    ...
}
let Connect = connect(mapStateToProps)(SubComponent);

Connect.mSup;   // undefined 

当然Facebook并不鼓励使用继承来创建特定组件,而是通过组合实现容器组件和高阶组件

猜你喜欢

转载自www.cnblogs.com/starryi-alpha/p/9279060.html
今日推荐