Newbie009 Newbie009 - 24 days ago 10
TypeScript Question

Javascript ES6(ES2015)/ Typescript: how to access local method inside static method

I basically want to access the "foo2" method inside a static "bar" method, but so far I only able access "foo1" and "foo3" method only. Can anyone teach me how can I access the non static foo2 method.

let foo1 = () => {
alert('foo1’);
};

class ABC extends Component {

static bar() {
foo1(); //can work

foo2; //not work with error "Can't find variable foo2"

foo2(); //not work with error "Can't find variable foo2"

this.foo2(); //not work with error "this.foo2 is not a function"

this.foo2; //no error but no alert, basically nothing happen

ABC.foo3() //can work
}

foo2 = () => {
alert('foo2');
};

static foo3 = () => {
alert('foo3');
};

}

module.exports = ABC;

Answer

WARNING: accessing instance-methods from static-methods is not desired, it might confuse other developers. Try to avoid using it. If you do use it - make sure your code is well commented and explains how does it work.

What you want to do is to bind the static method with context of the object which method you want to invoke from static method. You can do this by invoking it with call method:

class ABC extends Component {
    static bar () {
      this.foo();
    }
    foo () {
      // function body
    }
}

let instance = new ABC();
ABC.bar.call(instance);

or using bind if you want to pass the function like callback, etc, pre-bind it, so to speak:

let instance = new ABC();
setTimeout(ABC.bar.bind(instance), 1000);

NOTE: this by default references your class, not instance of the class (it will reference an instance after we bind it), so if you want to call another static method from the first static method you want to use full class name.

static bar () {
  this.foo();
  ABC.someOtherStaticMethod();
}

ALSO NOTE: if you use Typescript you will get an error when referencing instance-method, because this in your static method by default reference your class. To work-around this you might want cast this's type to any:

static bar () {
  (<any>this).foo();
}

Here you tell Typescript compiler something like "presume that this is not our class but something we don't know" just to get rid of error on compile time.