javascript - 对象字面量中的范围
问题描述
为什么在示例一中未定义,但在示例二中定义?我认为箭头符号将允许绑定在更高的范围内,在这种情况下是对象文字。
示例 1:
var runApp = {
init: () => {
console.log(this); //this is an empty object.
this.run() //will crash here, run not a function of this.
},
run: () => {
console.log("It's running!");
}
};
// Now we call init
runApp.init();
示例 2:
var runApp = {
init: function(){
console.log(this);
this.run()
},
run: function() {
console.log("It's running!");
}
};
// Now we call init
runApp.init();
解决方案
这是因为您使用的是箭头功能。箭头函数将始终保持其语法定义的上下文。在您的示例中,这很可能是init
未定义函数的窗口或全局对象。
非箭头函数将根据它们被引用的对象动态确定上下文。除非上下文已在.bind
较早时明确设置为低谷,或者低谷.apply
或.call
在调用站点。
推荐阅读
- php - 在服务提供者中合并到请求的参数在服务提供者之外丢失 - Laravel 5.6
- r - 运行 GEE 后,系数表不显示两个自变量的结果
- apache - 致命错误无法分配 134217728 字节的共享内存段:mmap:无法分配内存 (12)
- firebase - Firestore 侦听器的异常
- java - 改进我的键盘输入 (KeyListener) Java
- excel-2016 - 在 excel 中比较两个日期会返回错误的结果
- javascript - 从输入中修复位置 JSON
- python - 输出没有得到字符串 + 整数
- android - 我可以用 Expo 编辑 android:launchMode="singleTask" 吗?(反应原生)
- python - 将字符串拆分为单词