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);
}
}
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.