Joyce Babu
Joyce Babu

Reputation: 20654

Class property as a statement in ES6

In the following code, what is the purpose of writing the class properties as statements (3 commented lines)? Is it property initialization?

 export default class Player extends Camera {
   constructor(opts = {}) {
    super(opts);
    if(opts.target)
      this.setTarget(opts.target);
    this.movie;          // 1
    this.currentFrame;   // 2
    this.displayer;      // 3
    ...

Original Source

Upvotes: 1

Views: 73

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

They do nothing whatsoever in terms of the code itself assuming they aren't defined as getters (they aren't in the code you've quoted). (If they're getters and being called for their side-effects, that would be poor coding on multiple levels... :-) )

But IDEs sometimes infer the properties available on objects created by constructor functions or classes based on what properties are referenced on this within the constructor, so the author may have done this to improve the IDE's auto-suggest feature while editing. E.g., they do const p = new Player() and the IDE knows, from the constructor code, to offer movie, currentFrame, and displayer when he/she types p.. (A better option would be to set them to some appropriate initial value, even if undefined; that code won't create the properties on the actual object.)

Alternately, the author was just inexperienced with JavaScript and thought he/she had to "declare" the properties in some way, found that doing what you've shown didn't cause an error, and so assumed it was right.

Upvotes: 5

Related Questions