Prototype equivalent in ES6

I am starting to work in ES6 with a background in JavaScript. I have a question. I have an ES6 class, for example:

class User{ constructor(){ } doSomething(){ } } 

My questions: is the doSomething get doSomething created every time we instantiate this object? In the previous JS, we could take out doSomething and create it using "prototype" to ensure that doSomething is created once, and not every time we instantiate an object. However, I have no doubt in the right way to achieve the same effect in ES6. Any help would be appreciated.

+5
source share
2 answers

My questions are: is the "doSomething" method created every time we create this object?

No. The syntax class more or less like syntactic sugar for a constructor function + prototype. That is, the result is (almost) equivalent:

 function User() {} User.prototype.doSomething = function() { }; 

Look at the result Chrome produces:

enter image description here

However, I have no doubt in the right way to achieve the same effect in ES6.

As said, class does this for you. The whole point of introducing a class is to simplify the creation of design functions and customization methods for prototype (hence syntactic sugar).


If you want to know more, take a look

  • MDN - Classes

    JavaScript classes introduced in ECMAScript 6 are syntactic sugar compared to existing JavaScript prototypes. The class syntax is not representing a new object-oriented inheritance model for JavaScript. JavaScript classes provide a much simpler, more understandable syntax for creating objects and handling inheritance.

  • YDKJS - ES6 and Beyond

+11
source

Absolutely not. Apparently not a more connecting method for prototyping manually in ES6, but the fact of ES6 helps us do this in the background.
As MDN says:

JavaScript classes introduced in ECMAScript 6 are syntactic sugar compared to existing JavaScript prototypes. The class syntax does not represent a new object-oriented inheritance model for JavaScript. JavaScript classes provide a much simpler, more understandable syntax for creating objects and handling inheritance.

+3
source

Source: https://habr.com/ru/post/1261419/


All Articles