ES6 Class 转 ES5 实现
ES6 示例代码
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} is eating`);
}
static sleep() {
console.log("Sleeping");
}
}
class Dog extends Animal { // 原型链继承 + 静态方法继承
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
super.eat(); // 调用父类构造函数
console.log("Woof!");
}
}
ES5 代码实现
// 父类Animal
function Animal(name) {
this.name = name;
}
// 实例方法
Animal.prototype.eat = function() {
console.log(this.name + " is eating");
};
// 静态方法
Animal.sleep = function() {
console.log("Sleeping");
};
// 子类Dog
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// 继承原型链
Object.setPrototypeOf(Dog, Animal); // 静态方法继承
Dog.prototype = Object.create(Animal.prototype, {
constructor: {
value: Dog,
enumerable: false, // 方法自动绑定
}
});
// 子类方法
Dog.prototype.bark = function() {
Animal.prototype.eat.call(this);
console.log("Woof!");
};
转换点
ES6 | ES5 |
---|---|
class | 构造函数 + 原型方法 |
extends | Object.create() + Parent.call() |
super | Parent.call(this, args) |
super.method() | Parent.prototype.method.call(this) |
静态方法 | 直接挂载到构造函数上 |
原型方法默认是不可枚举的 | enumerable: false |
附加点:
虽然class的原型方法默认不可枚举,但可以通过Object.defineProperty()
方法将enumerable
属性设置为true
,这样就可以遍历到这些方法了:
Object.defineProperty(obj, 'testMethod', {enumerable: true});
console.log(Object.keys(obj)); // ['testMethod']