问题
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()?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/43062732/passing-this-from-call-to-arrow-function