CelestialEX
CelestialEX

Reputation: 106

Generic keyword to reference the class when calling a static function in JavaScript

I want to know if there is a generic keyword similar to this to reference the class when calling a static function from within a jQuery function for example like:

class MyClass {
    static FunctionA() {
        $('#someID').on('click', function() {
            this.FunctionB(); // Error here since 'this' here refers to the selected DOM element.
            MyClass.FunctionB(); // This works, but requires maintenance.
        });
    }

    static FunctionB() {
        this.FunctionC(); // Works here as 'this' refers to MyClass.
    }

    static FunctionC() {
    }
}

MyClass.FunctionA();

I basically want to know if we can somehow replace MyClass.FunctionB(); with something that will be valid regardless if the class name changes? Forgot to say that I don't want to do let classObject = this; to use it for the call within the jQuery function. That would be too easy.

Upvotes: 0

Views: 72

Answers (1)

javascwipt
javascwipt

Reputation: 1178

Your anonymous funciton needs to be bound in order for it have the correct this

class MyClass {
    static FunctionA() {
      $('#someID').on('click', function () {
        this.FunctionB(); // Error here since 'this' here refers to the selected DOM element.
        MyClass.FunctionB(); // This works, but requires maintenance.
      }.bind(this));
    }

    static FunctionB() {
      this.FunctionC(); // Works here as 'this' refers to MyClass.
    }

    static FunctionC() {
      console.log('works')
    }
  }

  MyClass.FunctionA();

You can also make use of the lexical this functionality of arrow functions and you will have no need for bind

  class MyClass {
    static FunctionA() {
      $('#someID').on('click', () => {
        this.FunctionB(); // Error here since 'this' here refers to the selected DOM element.
        MyClass.FunctionB(); // This works, but requires maintenance.
      });
    }

    static FunctionB() {
      this.FunctionC(); // Works here as 'this' refers to MyClass.
    }

    static FunctionC() {
      console.log('works')
    }
  }

  MyClass.FunctionA();

Upvotes: 1

Related Questions