1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
Dev
  • 181
  • 1
  • 13
  • 1
    Fat arrow functions don’t receive `this` from the call site, but from their surrounding scope. – user3840170 May 14 '21 at 18:40
  • Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – xdhmoore May 14 '21 at 18:42

4 Answers4

4

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();
Naren
  • 4,152
  • 3
  • 17
  • 28
0

The MDN states that:

Arrow functions does not have its own bindings to "this", and should not be used as methods.

Arrow functions establish "this" based on the scope the Arrow function is defined within.

Thus in this case the "this" will not be the "test" object.

MiccWan
  • 26
  • 2
0

The reason is that arrow functions don't bind their own this context, instead this will still be window

Try test.mySecondFunction('data') instead

devnull69
  • 16,402
  • 8
  • 50
  • 61
0

Arrow functions do not bind their own this, they inherit their this from the parent scope ("lexical scoping").

So, in regular functions the scoped is bound to the global one by default. arrow functions on the other hand, do not have their own this but they inherit it from the parent scope, (in this case the global one)

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

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

test.myFirstFunction();
Ran Turner
  • 14,906
  • 5
  • 47
  • 53