问题
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