【发布时间】:2020-01-11 05:39:17
【问题描述】:
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);
}
}
【问题讨论】:
-
以及您询问的代码...babeljs.io/…
-
这是一个关于prototypal inheritance from MDN的好指南
-
是的。类符号只是语法糖。实际上,您可以使用 ES5 代码做更多事情。例如,类表示法不支持类的静态数据,并且使用 ES5 语法,您可以使用命名函数(因此函数可以调用自身)。如果需要,您可以将两者混合使用。
标签: javascript class inheritance ecmascript-6 prototype