Passing this from .call() to arrow function [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-01 22:57:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!