5

I have an arrow function that I am trying to execute with call(). For the sake of simplification, as follows:

Operational as expected

const func = (e) => {
    console.log(e)
}

func.call(null, e)

Hmm ... what's going on here?

I would expect the following code to pass element into func as this.

const func = (e) => {
    console.log(this)
    console.log(e)
}

func.call(element, e)

But, instead this remains undefined.

If I switch it to a regular function definition, all works as expected.

const func = function (e) {
    console.log(this)
    console.log(e)
}

func.call(element, e)

Question

Why am I not able to pass a context for this into an arrow function from call()?

Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52

2 Answers2

14

this is not bound in arrow functions, so call() and apply() can only pass in parameters. this is ignored

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Invoked_through_call_or_apply

AJ Funk
  • 3,099
  • 1
  • 16
  • 18
  • 1
    Great innit, and then eslint says it's got an issue with all function() and to use arrow ones. So where we had a let root = this; solution we now have a, Oh look we can't use call or apply now. Unless you remove the check from eslint for function, but airbnb lint is set to warn about functions. – Pocketninja Mar 14 '18 at 02:44
4

In ES6 this has lexical scope meaning value of this inside arrow function would be same as that outside of arrow function. In pre-ES6 form this is the object that you passed as a first argument to call method.