DEV Community

Discussion on: Best way to write class methods in javascript?

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

I personally prefer the first approach, because:

  • If you want to use the super keyword, you actually have to do it that way. The super keyword is only allowed in class expressions and object literals, so the second style will generate a syntax error if you try to use the super keyword in the method.
  • It makes it much clearer that the method is part of the class, and also makes the binding of the this keyword a bit more explicit.
  • It plays nicer with documentation tools. Most tools for generating documentation from JavaScript code properly understand in the first case that 'bark' is an instance method of the Dog class. A few of them will need some help to understand that that's the case in the second example.
  • It's generally more concise, leading to smaller code in production (and minifiers can't do this transform themselves, since they can't gaurantee it won't change the semantics of the code). This in turn translates to faster loading (less code to download) and faster parsing (less code to parse).
  • Parsing the first example should be faster in most cases on a well written JS engine even aside from the code size aspect. In short, the syntax used in the first example can only be used for assigning functions to the class prototype, so the JS engine can skip a whole lot of special cases in the normal assignment code path. I don't know if this actually matters on any widely used JS engine today, but it's still worth considering.

It's important to realize though that there are some limitations to the first example:

  • You can't use it to define static methods. Everything in a class expression becomes part of the prototype, so you can't define static methods this way.
  • You can't use it to define static properties or class variables. Neither situation is well supported in JavaScript anyway (in both cases, the functions that need to access them have to use the class name, they can't get them off the prototype or use a keyword), but they still can't be defined this way right now in JS (though there is a TC39 proposal for class variables as part of a class definition).
  • You have to explicitly define the function in the class expression. In short, you can't assign an existing function as a method in a class expression. This (usually) isn't an issue, but it's still worth remembering.

Note also that neither example will work in Internet Explorer, Opera Mini, or old pre-Chrome Android browser versions. Overall market share for ES6 class support is just over 90% right now though, so unless you need Internet Explorer support, either will work.

Collapse
 
numtostr profile image
Vikas Raj

Thanks for lovely reply.

After your reading your explanation, I think that the first approach is faster.