回调箭头函数不会从其父函数继承“this”,**this 不是重复的**

Callback arrow function does not inherit 'this' from it's parent function **this is not a duplicate**

提问人:Toffee Conmigo 提问时间:10/24/2020 更新时间:10/24/2020 访问量:244

问:

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

我浏览了 ES6 中箭头函数中的“this”指的是什么?但没有找到答案。

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 回调 这个 arrow-functions

评论


答:

2赞 CertainPerformance 10/24/2020 #1

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

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

你说得对

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

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

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

使用箭头函数,只需查看外部环境即可查看内部环境所指的内容:thisthis

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

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

评论

0赞 Toffee Conmigo 10/24/2020
我知道我为什么错了。当 A.myf 执行时,它不会创建块。
0赞 Toffee Conmigo 10/24/2020
非常感谢@CertainPerformance。多亏了你的回答,我今晚才能睡个好觉。
0赞 Toffee Conmigo 10/24/2020
第一条注释应该是“当箭头函数加载到内存中时,A.myf 不会创建块。