I think that code is worth a thousand words. Take this example
class Cat {
constructor() {
this.meow("roar", this.sound)
}
meow(a, callback) {
callback(a)
}
sound(a) {
console.log(a)
console.log(this.sayMeow) <----- THIS IS UNDEFINED
}
sayMeow() {
return "Meow"
}
}
As you can see method sayMeow() is undefined. Can you please explain why and how can i solve it?
This is just simplified representation of more complex code where i have to use callbacks. I need to know why method is undefined inside callback function. Please do not write modifications of this simple Cat class.
Thank you
Explanation
In JavaScript, the this is determined when a function is called. In your case, sound(a) is called with the this context of undefined.
if you insist on using this inside sound(a), there are two common solutions:
this context in the constructorThe first approach was popularized by React, and it worked fine because user-created React components are meant to be final classes. However, if you are doing object-oriented programming and you expect your Cat class to be inherited from, you cannot use this approach for it breaks inheritance.
Solution
Bind the context of execution to the instance of your class in the constructor.
class Cat {
constructor() {
this.sound = this.sound.bind(this)
this.meow("roar", this.sound)
}
meow(a, callback) {
callback(a)
}
sound(a) {
console.log(a)
console.log(this.sayMeow)
}
sayMeow() {
return "Meow"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With