【问题标题】:Passing this from .call() to arrow function [duplicate]将其从 .call() 传递给箭头函数[重复]
【发布时间】:2017-08-21 02:59:01
【问题描述】:

我有一个箭头函数,我想用call() 执行它。为简化起见,如下:

按预期运行

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

func.call(null, e)

嗯……这是怎么回事?

我希望以下代码将element 传递给func 作为this

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() 的箭头函数?

【问题讨论】:

  • 出于兴趣,您为什么决定使用箭头函数而不是常规函数?
  • @CodingIntrigue 没有理由,纯粹是我注意到这种行为的实验。

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

在 ES6 中 thislexical scope 意思是 this 内部箭头函数的值与箭头函数外部的值相同。在 ES6 之前的形式中,this 是您作为第一个参数传递给 call 方法的对象。

【讨论】:

    【解决方案2】:

    this没有绑定在箭头函数中,所以call()apply()只能传入参数。 this 被忽略

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

    【讨论】:

    • 伟大的 innit,然后 eslint 说所有 function() 和使用箭头函数都有问题。所以我们有一个 let root = this;解决方案我们现在有一个,哦,看我们现在不能使用 call 或 apply。除非您从 eslint 中删除检查功能,但 airbnb lint 设置为警告功能。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2018-06-26
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 2016-05-23
    • 2020-02-20
    相关资源
    最近更新 更多