Are ES6 classes the same as constructor functions?

此生再无相见时 提交于 2021-02-19 08:46:10

问题


As I understand it: ES6 classes are basically constructor functions, right?

Of course with the benefit of not having to write stuff like this:

myFunction.prototype.myInheritablemethod= "someMethod";

Is this correct?

I'm asking because I'm aware there is the module pattern and the revealing module pattern, but those are not what ES6 classes are about, right?


回答1:


Classes were introduced to provide syntactic sugar around the existing prototypal inheritance model of JavaScript. The following...

class Example {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  add() {
    return this.a + this.b;
  }
}

...is basically equivalent to this:

function Example(a, b) {
  this.a = a;
  this.b = b;
}
Example.prototype.add = function() {
  return this.a + this.b;
};

The class syntax along with the other bits it provides (like extends and static) makes it much easier and clearer to write code that deals with inheritance. But since it's just sugar around existing techniques it would probably make sense for you to properly understand pre-ES6 inheritance first.



来源:https://stackoverflow.com/questions/37180286/are-es6-classes-the-same-as-constructor-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!