Can ES6 class inheritance be translated into equivalent ES5 code?

狂风中的少年 提交于 2021-02-05 11:46:39

问题


This answer shows how a simple ES6 class:

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

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

is equivalent the following ES5 code:

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

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

Is is similarly possible to translate ES6 class inheritance to ES5 code? What would be the ES5 equivalent to following derived class?

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

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

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

回答1:


The equivalent in the sense of how it was done before (ignoring exact behaviours like property enumerability and extending actual ES6 classes from ES5-compatible code) was to:

  • set the child prototype to a new object inheriting the parent prototype
  • call the parent constructor from the child constructor
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);
};

It was also possible to inherit properties of the constructor (“static”) using the de facto facility for modification of existing prototypes: B.__proto__ = A



来源:https://stackoverflow.com/questions/59691972/can-es6-class-inheritance-be-translated-into-equivalent-es5-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!