在仅限客户端的应用程序中,我正在加载两个带有脚本标记的 js 文件,一个接一个,并收到如下评论中所示的错误:
obj.js
'use strict';
let obj = {};
obj.func1 = () => {
return 'stuff';
}
obj.func2 = (arr) => {
debugger; // in devtools, value of 'this' is obj, as expected
console.log(this); // clicking 'next' button in devtools,
// the object that is actually being printed to
// console is the window object!!!
// javascript, wtf?!?!
debugger;
let myStuff = this.func1(); // fails because window has no 'func1' property
...
...
}
window.obj = obj;
脚本.js
'use strict';
obj.func2()
// Uncaught TypeError: this.func1 is not a function
到底为什么会发生这种事?为什么 devtools 调试器和浏览器中的实际结果之间的“this”值存在差异?
编辑:
请参阅下面的屏幕截图,当我自己在控制台中执行 console.log(this)
并被 debugger
断点暂停时,“this ' 是 Object(),下一步(相信我,这正是下一步),窗口对象被打印到控制台。
最佳答案
箭头函数中 this
的值在创建时隐式绑定(bind)。无论 this
在创建函数的上下文中是什么,都将是调用函数时 this
的值。
obj.func2 = (arr) => {
// ...
};
基本上相当于
obj.func2 = function(arr) {
// ...
}.bind(this);
关于javascript:调试器和实际结果之间的 'this' 值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361026/