【问题标题】:Callback arrow function does not inherit 'this' from it's parent function **this is not a duplicate**回调箭头函数不会从它的父函数继承“this”**这不是重复的**
【发布时间】:2020-10-24 05:58:37
【问题描述】:

这不是重复的,请不要再次关闭它。

我浏览了What does "this" refer to in arrow functions in ES6?,但没有找到答案。

class A{
    static myf(test){
          console.log(this); //when A.myf executes,  logs 'A'
          test();
     }
}

A.myf(()=>{
    console.log(this); // logs 'window'
})

有人可以帮我解决这个问题吗?在上面的例子中,箭头函数的词法环境是A.myf,箭头函数的'this'应该继承自myf的'this'。那么为什么要记录“窗口”而不是 A?

【问题讨论】:

    标签: javascript callback this arrow-functions


    【解决方案1】:

    每当输入另一个时,就会创建一个新的词法环境。

    块由{s 和}s 分隔 - 通常出现在函数的开头function foo() { 或循环的开头for (...) { while (...) {。 (对象字面量不是块。)

    你是对的when you say

    据我所知,箭头函数“this”从其词法环境继承作用域。

    这里有 2 个这样的环境(可以可视化为将标识符名称映射到该块中的值的容器):顶层的环境和回调内部的环境:

    // Here is the outer environment
    A.myf(()=>{
        // Here is the inner environment
        console.log(this); // logs 'window'
    })
    

    使用箭头函数,只需查看外部环境的this 即可了解内部环境的this 指的是什么:

    const outerThis = this;
    A.myf(()=>{
        console.log(outerThis === this); // this will ALWAYS be true
            // if the block is created from an arrow function
    })
    

    在草率模式下,this 是顶层的全局对象,所以this 在回调中是window

    【讨论】:

    • 我知道我为什么错了。当 A.myf 执行时,它不会创建块。
    • 非常感谢@CertainPerformance。感谢您的回答,我今晚可以睡个好觉了。
    • 第一个注释应该是“当箭头函数被加载到内存时,A.myf 不会创建块。”
    猜你喜欢
    • 2021-04-22
    • 2023-03-15
    • 2017-12-06
    • 1970-01-01
    • 2018-08-01
    • 2018-02-07
    • 2019-08-06
    • 2022-12-04
    相关资源
    最近更新 更多