I have a class with a method that accesses some instance properties of the class. I am trying to call this method by passing it as a callback to an outside function, but my approach causes the program to crash at runtime because the this
attribute is undefined
. From what I read, this could be because the function is defining its own this
, which is why I made it an arrow function, but that still doesn't resolve the issue. Here is an approximation of the code:
class Foo {
bar = 0;
modifyBar(value) {
this.bar = value; // TypeError: Cannot set properties of undefined (setting 'bar')
}
constructor() {
call(this.modifyBar);
}
}
const call = (callback) => {
// ...
callback(1);
};
const foo = new Foo();
I have tried using the method.call
attribute and passing in the class this
attribute, but to me that seems like a hack and unnecessarily verbose. My question is: what's the reason that this
evaluates to undefined
at runtime?
This is the code that achieves what I want using method.call
:
class Foo {
bar = 0;
modifyBar(value) {
this.bar = value;
}
constructor() {
call(this, this.modifyBar);
}
}
const call = (instance, callback) => {
// ...
callback.call(instance, 1);
};
const foo = new Foo();
console.log(foo.bar); // 1
P.S. I know that the way my logic is setup seems abstract, and that I could simply move call
into the class definition, but in my actual application it is more of a utility function that performs various side effects in different contexts. This is why I'm looking for a solution to do it exactly this way.