1

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?)

  • 1
    Classes are essentially (but not completely) syntactic sugar. They accomplish the same thing, but with easier-to-understand syntax. – Michael Bianconi Mar 30 '20 at 14:27
  • @MichaelBianconi So as you say whenever I use a class I also could just use an object constructor and vice versa? –  Mar 30 '20 at 14:28
  • 1
    At least related: [*What benefits does ES2015 (ES6) `class` syntax provide?*](https://stackoverflow.com/questions/30783217/what-benefits-does-es2015-es6-class-syntax-provide) – T.J. Crowder Mar 30 '20 at 14:28
  • 1
    [this article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model) might be helpful – wahwahwah Mar 30 '20 at 14:29
  • 1
    @Orange - *"So as you say whenever I use a class I also could just use an object constructor and vice versa?"* Very nearly (particularly if you use methods on `Reflect` in some places), but not quite. – T.J. Crowder Mar 30 '20 at 14:32
  • 2
    @Orange - Very clever, what you did with your display name there... :-) – T.J. Crowder Mar 30 '20 at 14:37

1 Answers1

3

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.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875