首页 > 解决方案 > ES6 类继承可以翻译成等效的 ES5 代码吗?

问题描述

这个答案展示了一个简单的 ES6 类:

class A {
  constructor() {
    this.foo = 42;
  }

  bar() {
    console.log(this.foo);
  }
}

等效于以下 ES5 代码:

function A() {
  this.foo = 42;
}

A.prototype.bar = function() {
  console.log(this.foo);
}

同样可以将 ES6 类继承转换为 ES5 代码吗?什么是 ES5 等价于以下派生类?

class B extends A {
  constructor() {
    super();
    this.foo2 = 12;
  }

  bar() {
    console.log(this.foo + this.foo2);
  }

  baz() {
    console.log(this.foo - this.foo2);
  }
}

标签: javascriptclassinheritanceecmascript-6prototype

解决方案


就其之前的实现方式而言(忽略属性可枚举性和从 ES5 兼容代码扩展实际 ES6 类等确切行为)的等价物是:

  • 将子原型设置为继承父原型的新对象
  • 从子构造函数调用父构造函数
function B() {
  A.call(this);
  this.foo2 = 12;
}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.bar = function () {
  console.log(this.foo + this.foo2);
};

B.prototype.baz = function () {
  console.log(this.foo - this.foo2);
};

也可以使用事实上的工具来继承构造函数的属性(“静态”)来修改现有原型:B.__proto__ = A


推荐阅读