Note: I do not want to re-bind the this keyword. I would like for this to reference the calling object. I would, however, also like to be able to reference the instance of the class in which my method is defined. How can I access the instance?
In JavaScript, the this keyword refers to the calling object. So, when I define a class:
class A {
x = 5;
printx() {
console.log(this.x);
}
}
Then when I call the printx method directly from an instance of A, I get 5:
a = new A();
a.printx();
But when I call printx from a different context, this.x isn't a.x, it might be window.x or something else:
b = a.printx;
b(); // TypeError: this is undefined
I want to define printx in such a way that calling b will console.log(5). I.e., I want to get the self behavior from Python. How do I refer to self in JavaScript?