ES6类继承可以转换为等效的ES5代码吗? [英] Can ES6 class inheritance be translated into equivalent ES5 code?

查看:50
本文介绍了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代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆