es6 class继承用es5实现

ES5日期对象继承
本文介绍了如何使用ES5实现日期对象的继承,并提供了一种改进的方法来解决V8引擎底层限制的问题。此外,还展示了ES6中实现日期继承的简化方式。

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());

复制代码

转载于:https://juejin.im/post/5b361a8c6fb9a00e45114ad6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值