此答案显示了一个简单的ES6类:
This answer shows how a simple ES6 class:
class A { constructor() { this.foo = 42; } bar() { console.log(this.foo); } }等效于以下ES5代码:
is equivalent the following ES5 code:
function A() { this.foo = 42; } A.prototype.bar = function() { console.log(this.foo); }是否有可能将ES6类继承转换为ES5代码?ES5与以下派生类等效吗?
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); } } 推荐答案从以前的意义上讲,这是等效的(忽略诸如属性可枚举之类的确切行为,并从与ES5兼容的代码中扩展实际的ES6类)是:
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:
- 将子原型设置为继承父原型的新对象
- 从子构造器中调用父构造器
还可以使用事实工具来继承构造函数的属性(静态"),以修改现有原型: B .__ proto__ = A
It was also possible to inherit properties of the constructor ("static") using the de facto facility for modification of existing prototypes: B.__proto__ = A
更多推荐
ES6类继承可以转换为等效的ES5代码吗?
发布评论