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

标签 javascript class inheritance ecmascript-6 prototype

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/

相关文章:

javascript - Facebook 页面不会自动调整为较小的内容

javascript - 自动化应用程序测试 (phantomjs) 和 merge 分支

Javascript原型(prototype)继承基函数未定义

c++ - 为什么它给出派生版本?

JavaScript 子类化和方法重写

javascript - Javascript 和 Angular 中的链式 Promise

javascript - 属性的类别属性

java - 是否可以打开包含类的 .txt/.java 文件,并对其使用反射?

C++ 如何显示/打印字符串对象? cout << int 有效,cout << string 无效

javascript - 无法选择 Javascript 附加的 HTML 元素