最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Equivalent of Prototype in ES6 - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Dec 17, 2016 at 5:10 user663031 asked Dec 17, 2016 at 2:46 fur866fur866 4132 gold badges5 silver badges14 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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

  • 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

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.

发布评论

评论列表(0)

  1. 暂无评论