首页 > 解决方案 > 有人可以向我解释为什么这些箭头函数中的关键字 `this` 以这些示例中的给定值结尾

问题描述

根据(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):

箭头函数没有自己的 this。使用封闭词法范围的 this 值;箭头函数遵循正常的变量查找规则。

下面是一些我认为箭头函数this错误的例子。(我没有将可运行代码嵌入到问题中,因为它给我的结果与我的代码编辑器不同 - 与节点一起运行的 Visual Studio 代码)。有人可以解释我的例子吗?

1.

f = param1 => console.log(this);

f(); //expected: global object prints: {}

2.

var bike = {
    owner: 'Adam',
    getOwner: () => {
        console.log(this.owner);
    }
};

bike.getOwner(); //expected: 'Adam' prints: undefined

标签: javascript

解决方案


箭头函数没有自己的 this。使用封闭词法范围的 this 值;箭头函数遵循正常的变量查找规则。

所以你需要考虑的是,this如果它不在它自己的功能中,会指的是什么?

所以如果我们有一个IIFE,比如:

(() => console.log(this.foo))();

这相当于

console.log(this.foo)

因此,使用您的示例:

var bike = {
    owner: 'Adam',
    getOwner: (() => {
        console.log(this.owner);
    })()
};

相当于:

var bike = {
    owner: 'Adam',
    getOwner: console.log(this.owner)
};

显然,this.owner不存在。

您还可以将箭头函数视为常规函数.bind(this)

this.tmp = 'a';

x = () => {
    console.log(this.tmp);
}

y = function() {
    console.log(this.tmp);
}.bind(this)

x();
y();


推荐阅读