问题
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