Reputation: 413
I am starting out in ES6 with background in JavaScript. I have a question. I have an ES6 class like the following:
class User{
constructor(){
}
doSomething(){
}
}
My questions is does doSomething
method get created each time we instantiate this object? In previous JS, we could take out doSomething
and create it with "prototype" to ensure that doSomething
is created once, not every time we instantiate the object. However, I am note sure about the correct way to achieve the same effect in ES6. Any help would be appreciated.
Upvotes: 10
Views: 10157
Reputation: 617
Absolutely not. It seems no more binding method to prototype manually in ES6, but the fact is ES6 helps us to do that in background.
As MDN says:
JavaScript classes introduced in ECMAScript 6 are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
Upvotes: 3
Reputation: 816404
My questions is does "doSomething" method get created each time we instantiate this object?
No. The class
syntax is more or less just syntactic sugar for constructor function + prototype. I.e. the result is (almost) equivalent to:
function User() {}
User.prototype.doSomething = function() { };
Look at the result Chrome produces:
However, I am note sure about the correct way to achieve the same effect in ES6.
As said, class
does that for you. The whole point of introducing class
is to make creating constructor functions and setting methods on prototype
easier (hence syntactic sugar).
If you want to learn more, have a look at
JavaScript classes introduced in ECMAScript 6 are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
Upvotes: 15