ES6的class降级

文章讨论了如何将ES6的类语法转换为ES5的代码,包括类的声明、构造函数、静态属性、访问器方法和不可枚举属性。重点在于模拟ES6的特性,如类的实例和原型上的访问器以及方法的不可枚举性,并确保正确处理构造函数的调用方式。
摘要由CSDN通过智能技术生成

将下列ES6的代码降级为ES5

class Product {
static count = 0;
constructor(name, unitPrice, number) {
this.name = name;
this.unitPrice = unitPrice;
this.number = number;
Product.count++;
}
get totalPrice() { // ES6访问器,注意:会同时存在原型和实例上,而且不可枚举(控制台打印即灰色),不能被for-of、for-in等遍历到
return this.number * this.unitPrice;
}
increase() { // 注意:不可枚举,且只能当作普通方法调用,不能通过new形式(new product.increase(),只能product.increase()来使用)来调用
this.number++;
}
}
const product = new Product();
分析:

  1. class同let、const,有作用域死区,即先声明再使用,没有变量提升

  2. class必须通过new来进行调用,否则就会报错

  3. ES6访问器不可枚举,同时会存在在圆形和实例上

  4. ES6的方法不可枚举,同时只能当作普通方法调用,不能通过new形式来调用

  5. ES6的继承是先将父类实例对象的属性和方法,添加到this上(所以必须先调用super()方法),然后再调用字累的构造函数修改this;ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上。class继承可以实现与安生构造函数的继承,而ES5的不可以。

var Product = (function (_Parent) {
_Parent && inherits(Product, Parent);
function Product(name, unitPrice, number) {
if (Object.getPrototypeOf(this) !== Product.prototype) { // 当然也是可以绕开,如:var p = Product(); Product.call§;
// if (this.protyo !== Product.prototype) { // ES不推荐使用__proto

// if (!new.target) { // ES6写法
throw new TypeError(‘不能不使用new来调用’);
}
this.name = name;
this.unitPrice = unitPrice;
this.number = number;
Product.count++;
}
Object.defineProperty(Product.prototype, ‘totalPrice’, {
get() {
this.number * this.unitPrice;
},
enumerable: false,
});
Object.defineProperty(this, ‘totalPrice’, {
get() {
this.number * this.unitPrice;
},
enumerable: false,
});
Object.defineProperty(Product.prototype, ‘increase’, {
value: function () {
if (Object.getPrototypeOf(this) !== Product.prototype.increase.prototype) { // 当然也是可以绕开,如:var p = Product(); Product.call§;
/*
new product.increase(); increase的this指向了increase的实例
product.increase(); // increase的this指向了product
通过以上,判断this指向是不是相同即可
*/
throw new TypeError(‘不能不使用new来调用’);
}
this.number++;
},
enumerable: false,
});
Product.count = 0;
// Product.prototype.increase = function () { // 不能这么创建,不然increase会被枚举
// this.number++;
// }
return Product;
})();

function _inherits(subClass, superClass) {
if (typeof superClass !== ‘function’ && superClass !== null) {
throw new TypeError('superClass expression must either be null or a function, not ’ + typeof superClass);
}
// 利用寄生继承继承父类原型
superClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
}
})
// 将子构造函数的__proto__指向父类构造函数,这里的setPrototypeOf方法和create类似,可以看出class继承同时存在两条继承链:子类构造函数的__proto__指向父类,子类原型的__proto__指向父类原型
if (superClass) {
Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.proto = superClass;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值