2

I'm trying to call a static method on a class from a reference to that method, but the "this" variable is undefined when I do it that way:

class SomeClass {
  static test() {
    console.log(this);
  }
}

SomeClass.test(); // logs reference to class as desired
let fn = SomeClass.test;
fn(); // logs undefined
let fn2 = () => { SomeClass.test(); }
fn2(); // logs reference to class as desired

Why is "this" undefined in the fn() call? Is there a way to make sure its defined? Wrapping the method in an anonymous function like in fn2() works as a work around but is a bit ugly. Is this behavior with fn1 giving this undefined by design in Javascript?

C.J. Windisch
  • 81
  • 1
  • 4

0 Answers0