I am trying to call a public member function from a static variable this so typescript:
class myClass {
static myTmp: myClass;
constructor(elem: HTMLElement) {
elem.addEventListener(“mousedown”, this.callThis);
}
public setTmp() {
myClass.myTmp = this;
}
public callThis() {
myClass.myTmp.myMethod();
}
public myMethod() {
console.log("Hello World!");
}
}
But I keep getting myClass.myTmp.myMethod is not a function.
This example may seem weird, but it makes sense in my real problem. I have tried doing it through a global variable as well, but still no luck. I would like to keep it all within one class. Am I missing something major here?
EDIT: This is what I was trying to do, and this works:
class myClass {
static myTmp?: myClass;
constructor(elem: HTMLElement) {
elem.addEventListener(“mousedown”, this.callThis.bind(this));
}
public setTmp() {
myClass.myTmp = this;
}
public callThis() {
myClass.myTmp?.myMethod();
}
public myMethod() {
console.log("Hello World!");
}
}
I then have a list of myClass'es and at some point "setTmp" is called, enabling the "myMethod" method.
elem.addEventListener('mousedown', () => this.callThis())thisin the event handler is the element and not the object. You can storethisto a variable first and then use it. Eg:var self = this;elem.addEventListener("mousedown", this.callThis.bind(this));instead.