Search code examples
javascriptthisarrow-functions

JavaScript - Object Functions


I have a JavaScript object that's defined like this:

const test = {
  myFirstFunction: () => {
    console.log('MyFirstFunction called');
    this.mySecondFunction('data');
  },

  mySecondFunction: (param) => {
    console.log('MySecondFunction called ' + param);
  }
};

test.myFirstFunction();

When I run this code, I receive an error that says:

"Uncaught TypeError: this.mySecondFunction is not a function".

I don't understand why. What am I doing wrong?


Solution

  • Arrow function doesn't have own this, it defaulty points to parent this.

    In your myFirstFunction & mySecondFunction parent is window. when you call this.mySecondFunction() is actually looking for window.mySecondFunction() which is not there. That's why it throwing an error.

    Change it to normal function, it will work fine.

    const test = {
      myFirstFunction: function() {
        console.log('MyFirstFunction called');
        this.mySecondFunction('data');
      },
    
      mySecondFunction: function(param) {
        console.log('MySecondFunction called ' + param);
      }
    };
    
    test.myFirstFunction();