javascript - 有人可以向我解释为什么这些箭头函数中的关键字 `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
解决方案
箭头函数没有自己的 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();
推荐阅读
- arrays - 如何正确地将某些内容附加到数组中?
- django - 如何修复'AttributeError:'Person'对象在Django is_valid()方法中没有属性'_default_manager'
- react-native - 从 store redux 获取状态值
- angular - 子隐藏时防止在父 div 上重新触发 mouseenter
- java - 如何使用 Java 从 Google Cloud Storage 服务器端的视频创建缩略图或 jpeg 图像
- python - 无法通过来自 API 的请求检索成功响应
- reactjs - 如何返回此状态
- r - 如何使用 R 读取 json 文件的前几条记录?
- amazon-web-services - 复制任务设置 JSON 上的 Boto3 DMS 'modify_replication_task' 错误
- python - string5 = "{:~^10}" 会对给定的字符串做什么?