ES5实现ES6中的class

本文详细介绍如何使用ES5的语法特性,如Function、Object.defineProperty等,来模拟实现ES6中Class的定义方式,包括构造函数、原型方法及静态方法。

用ES5实现ES6中的class;

function _defineProperties(target,prop){
        prop.forEach(ele => {		//可能会传入多个属性
            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)
    }
}

function _classCallCheck(_this,_constructor){
    if(!(_this instanceof _constructor)){     //判断是否是通过new(创建实例)来调用_constructor
            throw "TypeError: Class constructor AirPlane cannot be invoked without 'new'"
    }
}
var FatherPlane=(function(){
    function FatherPlane(name,color){
        _classCallCheck(this,FatherPlane)
        this.name=name||'liu';
        this.color=color||'red'
    }
    _createClass(FatherPlane,[
        {
            key:'fly',
            value:function(){
                console.log('fly')
            }
        }
    ],[
        {
           key:'static',
           value:function(){
               console.log('static')
           } 
        }
    ])
    return FatherPlane;
})()
var airplane=new FatherPlane()

    

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值