JavaScript 将ES6 class类 降级改写成ES5构造函数
//ES6 Product类 class Product{ //声明静态变量 static count=0; //构造函数属性 constructor(name,unitPrice,number){ this.name=name; this.unitPrice=unitPrice; this.number=number; Product.count++; } //访问器属性 get totalPrice(){ return this.number*this.unitPrice; } //定义类的方法 increase(){ this.number++; } } //用ES5 改写 //模拟ES6类的作用域死区 用立即执行函数包起来 防止在没有实例化之前直接调用 例如:Product2() =>undefined var Product2=(function(){ //构造函数参数 function Product2(name,unitPrice,number){ //禁止直接调用构造函数 通过判断当前实例的原型__proto__是否等于构造函数的原型Product2.prototype // if(this.__proto__!==Product2.prototype){ //不建议直接使用this.__proto__来访问原型,用官方推荐的写法改写如下 if(Object.getPrototypeOf(this)!==Product2.prototype){ throw new TypeError("Class constructor Product cannot be invoked without 'new'") } this.name=name; this.unitPrice=unitPrice; this.number=number; Product2.count++; //构造函数实例上 定义不可枚举的访问器属性 Object.defineProperty(this,'totalPrice',{ get(){ return this.number*this.unitPrice; }, //不可枚举 enumerable:false }) } //声明静态变量 Product2.count=0; //构造函数原型上 定义不可枚举的访问器属性 Object.defineProperty(Product2.prototype,'totalPrice',{ get(){ return this.number*this.unitPrice; }, enumerable:false }) //构造函数原型上 这样定义的方法 会被枚举 // Product2.prototype.increase=function(){ // this.number++ // } //构造函数原型上 定义不可枚举的访问器方法 Object.defineProperty(Product2.prototype,'increase',{ value: function increase(){ //禁止构造函数方法直接使用new 来调用 例如:let p2=new Product2(1,2,3);使用new p2.increase()调用这个方法抛出错误 if(Object.getPrototypeOf(this)===Product2.prototype.increase.prototype){ throw new TypeError("increase is not a constructor") } this.number++ }, enumerable:false }) return Product2; })()