ES5实现ES6中的class
程序员文章站
2023-12-21 13:15:22
...
用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()