目录

ES6-Class-转-ES5-实现

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!");
};

转换点

ES6ES5
class构造函数 + 原型方法
extendsObject.create() + Parent.call()
superParent.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']