0

First, before this question will be downvoited, as you know in ES6 classes keyword static don't works for class properties. However, we can define it via get methods, as in the example below.

I learned that we can to call the static property inside the class by calling booth class name and this:

class Animation{

  static get SLOW (){ return 900; } // milliseconds
  static get FAST (){ return 300; } // milliseconds

  static getSlowSpeedValue(){
    console.log(this.SLOW); // works
    //console.log(Animation.SLOW); // works too
  }
}

Animation.getSlowSpeedValue();

Which method is technically right, which is the better practice?

By the way I also learned that we call any static methods inside the class by booth above ways:

class SomeClass{

   static method1(){
        SomeClass.method2(); // works
        //this.method2(); // works too
    }

    static method2(){
      console.log('OK');
    }
}

SomeClass.method1();
Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124
  • 2
    They're both "technically" correct, since they both work, but using `this` will have a higher mental burden (since it changes depending on the context), though it allows you to call that function with a different `this` value if you choose to use `.call`, `.apply` or `.bind`. – 4castle Oct 27 '17 at 00:15
  • 1
    `Animation.SLOW` due to the way scope & prototype chaining. This one is also faster, because doing `this` means it will check there first, if not found it will go to the prototype, by doing `Animation.SLOW`, you've skipped that bit and gone straight for the prototype. – Keith Oct 27 '17 at 00:18
  • @Keith, it's an answer, thank you! IMHO `this` for the static properties is not comfortable because in other PL `this` inside class is the instance calling, so the calling by class name as in Java PL is better. Do you agree? – Takeshi Tokugawa YD Oct 27 '17 at 00:26
  • 1
    @Keith: Uh? `this` and `Animation` refer to the same value. The property is defined on the function object itself, not on its prototype, so the prototype is never looked at. – Felix Kling Oct 27 '17 at 05:16
  • @FelixKling Oh, right never really looked at the `static` stuff in classes, for some reason assumed prototype. But looking in Chrome FAST and SLOW are attached to the `constructor` instance of the prototype, makes sense when you think about it. – Keith Oct 27 '17 at 07:31

0 Answers0