es6 class繼承用es5實現

蘆夢宇發表於2018-06-29

es5實現普通的繼承 // 類的呼叫檢測 檢測例項是不是new出來的 function _classCallCheck(instance, constructor) { if (!(instance instanceof constructor)) { throw new Error('Class constructor Child cannot be invoked without new') } }

const extend = (sub ,sup) => {
    //靜態屬性以及方法繼承
    Object.setPrototypeOf(sub, sup);
    sub.prototype = Object.create(sup.prototype);
    sub.prototype.constructor = sub;
    sub.super = sup.prototype;
    if(sup.prototype.constructor === Object.prototype.constructor) {
        sup.prototype.constructor = sup;
    }
};

function MyDate1(...args) {
    _classCallCheck(this,MyDate1);
    MyDate1.super.constructor.apply(this, args);
}
extend(MyDate1, Parent);

複製程式碼

es5實現日期繼承,直接使用上述方法會報錯,v8引擎底層程式碼中有限制,如果呼叫物件的[[Class]]不是Date,則丟擲錯誤。 改進如下:

es5 實現方案

const extend = (sub ,sup) => {
    //靜態屬性以及方法繼承
    Object.setPrototypeOf(sub, sup);
    //原型鏈繼承
    sub.prototype = Object.create(sup.prototype);
    //constructor更正
    sub.prototype.constructor = sub;
    //給兒子新增super屬性,指向父類原型
    sub.super = sup.prototype;
    if(sup.prototype.constructor === Object.prototype.constructor) {
        sup.prototype.constructor = sup;
    }
};


function MyDate2(...args) {
    _classCallCheck(this,MyDate2);
    const d1 = new MyDate2.super.constructor(...args);
    Object.setPrototypeOf(d1, MyDate2.prototype);
    return d1;
}

extend(MyDate2, Date);
const md3 = new MyDate2;
console.log(md3.getTime());

複製程式碼

附加:es6實現方法就很簡單了:

class MyDate extends Date{

}
const md1 = new MyDate();
console.log(md1.getTime());

複製程式碼

相關文章