Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS - class method is undefined in callback

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

like image 262
Raold Avatar asked Apr 09 '26 17:04

Raold


1 Answers

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:

  • use a class property function (an arrow function) instead of a method
  • bind the this context in the constructor

The 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"
    }
}
like image 127
Karol Majewski Avatar answered Apr 11 '26 09:04

Karol Majewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!