fur866
fur866

Reputation: 413

Equivalent of Prototype in ES6

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

Answers (2)

markjiang
markjiang

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

Felix Kling
Felix Kling

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:

enter image description here

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

  • MDN - Classes

    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.

  • YDKJS - ES6 & Beyond

Upvotes: 15

Related Questions