when to use class/object constructor

Ora nge :

I don't exactly get the difference between classes and object constructors in JS. As far as I see you can do quite similar things with them like defining functions or properties.

But what exactly is the difference and when to use which? (like is the constructor in the class similar to an object constructor?)

T.J. Crowder :

class syntax is mostly (but not entirely) syntactic sugar for creating constructor functions and filling in the object on their prototype property. You can do almost everything class does writing constructor functions explicitly and adding properties to their prototype property and using some methods on the ES2015+ Reflect object, but it's doing so is much more verbose and error-prone. (The number of things that you can only do with class syntax is going to increase before too long as the private fields and methods proposals mature.) I've given an overview of how class syntax can be emulated with earlier constructs in my answer to What benefits does ES2015 (ES6) class syntax provide? here.

As to when to use which, it's mostly a matter of style for you and your team to decide. Even for the things that you can't literally do without class syntax (such as private fields, which will likely advance to the living specification at some point this year and be in ES2021), you can do similar things in other ways.

But:

  • If what you're doing requires class syntax (for instance, if you want to use private fields, once they're added [or now via transpilation]) and you want to do that thing specifically rather than something else that's similar to it, then you'll need to use class syntax.
  • If not, it's largely a matter of style for you and your team to decide.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368256&siteId=1
Recommended