ES6类继承可以转换为等效的ES5代码吗?

编程入门 行业动态 更新时间:2024-10-27 04:37:09
本文介绍了ES6类继承可以转换为等效的ES5代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此答案显示了一个简单的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:

  • 将子原型设置为继承父原型的新对象
  • 从子构造器中调用父构造器
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); };

还可以使用事实工具来继承构造函数的属性(静态"),以修改现有原型: 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代码吗?

本文发布于:2023-07-24 13:25:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203708.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!