This answer展示了一个简单的 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);
}
}
最佳答案
与之前的做法相同(忽略诸如属性可枚举性之类的确切行为以及从 ES5 兼容代码扩展实际的 ES6 类):
- 将子原型(prototype)设置为继承父原型(prototype)的新对象
- 从子构造函数调用父构造函数
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);
};
还可以使用修改现有原型(prototype)的事实上的工具来继承构造函数(“静态”)的属性:B.__proto__ = A
关于javascript - ES6 类继承可以转换为等效的 ES5 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59691972/