将它从 .call() 传递给箭头函数
Passing this from .call() to arrow function
我有一个箭头函数,我正试图用 call()
执行它。为了简单起见,如下:
按预期运行
const func = (e) => {
console.log(e)
}
func.call(null, e)
嗯...这是怎么回事?
我希望以下代码将 element
作为 this
传递给 func
。
const func = (e) => {
console.log(this)
console.log(e)
}
func.call(element, e)
但是,this
仍然是 undefined
。
如果我将其切换为常规函数定义,一切都会按预期工作。
const func = function (e) {
console.log(this)
console.log(e)
}
func.call(element, e)
问题
为什么我无法将 this
的上下文传递到 call()
的箭头函数中?
this
没有绑定在箭头函数中,所以call()
和apply()
只能传入参数。 this
被忽略
在 ES6 中 this has lexical scope 意味着箭头函数内部 this
的值与箭头函数外部的值相同。在 ES6 之前的形式中,this
是您作为第一个参数传递给 call
方法的对象。
我有一个箭头函数,我正试图用 call()
执行它。为了简单起见,如下:
按预期运行
const func = (e) => {
console.log(e)
}
func.call(null, e)
嗯...这是怎么回事?
我希望以下代码将 element
作为 this
传递给 func
。
const func = (e) => {
console.log(this)
console.log(e)
}
func.call(element, e)
但是,this
仍然是 undefined
。
如果我将其切换为常规函数定义,一切都会按预期工作。
const func = function (e) {
console.log(this)
console.log(e)
}
func.call(element, e)
问题
为什么我无法将 this
的上下文传递到 call()
的箭头函数中?
this
没有绑定在箭头函数中,所以call()
和apply()
只能传入参数。 this
被忽略
在 ES6 中 this has lexical scope 意味着箭头函数内部 this
的值与箭头函数外部的值相同。在 ES6 之前的形式中,this
是您作为第一个参数传递给 call
方法的对象。