用ES5模拟实现ES6中的类

ES6中的类经过babel编译后会降级生成ES5的代码,用来兼容新老版本的浏览器。

通过看编译后的ES5的代码,自己来模拟实现一下ES6中的类。

主要模拟三点功能:

1.ES5中模拟类的构造函数不能直接执行,只能通过new来执行。

2.静态属性的模拟。

3.原型链上属性的模拟。


function _inherit (sub, sup) {
    Object.setPrototypeOf(sub.prototype, sup.prototype);
}


function _classCallCheck (_this, _constructor) {
    if (! (_this instanceof _constructor) ) {
        throw "TypeError: Class constructor Plane cannot be invoked without 'new'";
    }
};

// 处理公有属性和静态属性
// 
function _defineProperties (target, props) {
    // Object.defineProperty
    props.forEach(function (ele) {
        // ele.key ele.value
        Object.defineProperty(target, ele.key, {
            value: ele.value,
            writable: true,
            configurable: true
        });
    })
}

function _createClass (_constructor, _prototypeProperties, _staticProperties) {
    // 给原型上赋值
    if (_prototypeProperties) {
        _defineProperties(_constructor.prototype, _prototypeProperties);
    }
    if (_staticProperties) {
        _defineProperties(_constructor, _staticProperties);
    }
}

var Plane = (function () {
    function Plane (name) {
        // 判断是否以new的方式来执行
        _classCallCheck(this, Plane);
        this.name = name || '普通飞机';
        this.blood = 100; 
    }

    _createClass(Plane, [
        {
            key: 'fly',
            value: function () {
                console.log('fly');
            }
        }
    ], [
        {
            key: 'alive',
            value: function () {
                return true;
            }
        }
    ]);

    return Plane;
})();


var AttackPlane = (function (Plane) {
    
    _inherit(AttackPlane, Plane);
    function AttackPlane (name) {
        _classCallCheck(this, Plane);
        var _this = this;
        var that = Plane.call(_this, name);
        if (typeof that == 'object') {
            _this = that;
        }
        _this.logo = 'duyi';
        return _this;
    };

    _createClass(AttackPlane, [
        {
            key: 'dan',
            value: function () {
                console.log('biubiubiu');
            }
        }
    ], [
        {
            key: 'alive',
            value: function () {
                return true;
            }
        }
    ]);
    
    return AttackPlane;
})(Plane);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值