【发布时间】:2016-04-01 16:12:46
【问题描述】:
在一个仅限客户端的应用程序中,我正在加载两个带有脚本标签的 js 文件,一个接一个,并得到如下 cmets 中出现的错误:
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;
script.js
'use strict';
obj.func2()
// Uncaught TypeError: this.func1 is not a function
到底为什么会发生这种情况?为什么 devtools 调试器和浏览器中的实际结果之间的 'this' 值存在差异?
编辑:
请参阅下面的屏幕截图,当我在控制台中自己执行 console.log(this) 并被 debugger 断点暂停时,'this' is Object() 和一个下一步(相信我,这正是下一步),窗口对象正在打印到控制台。
【问题讨论】:
-
请附上这行截图:
debugger; // in devtools, value of 'this' is obj, as expected。为什么我的 devtool 显示this是window对象? -
@stanleyxu2005 IDK,我能够在 linux mint 上的 chrome beta (50) 和 OS X 上的 chrome canary (51) 中重现。您正在测试什么浏览器版本/操作系统?
-
这似乎与What does “this” refer to in arrow functions in ES6? 重复。调试器的东西似乎是一个无关的浏览器错误。
-
相关:Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 。同样是的,Chrome 中似乎存在一个错误,它没有在箭头函数中显示
this的正确值。
标签: javascript ecmascript-6 google-chrome-devtools javascript-objects