javascript:调试器和实际结果之间的 'this' 值不同

标签 javascript ecmascript-6 google-chrome-devtools javascript-objects

在仅限客户端的应用程序中,我正在加载两个带有脚本标记的 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(),下一步(相信我,这正是下一步),窗口对象被打印到控制台。

enter image description here

最佳答案

箭头函数中 this 的值在创建时隐式绑定(bind)。无论 this 在创建函数的上下文中是什么,都将是调用函数时 this 的值。

obj.func2 = (arr) => {
  // ...
};

基本上相当于

obj.func2 = function(arr) {
  // ...
}.bind(this);

关于javascript:调试器和实际结果之间的 'this' 值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361026/

相关文章:

javascript - Chrome 开发工具 Service Worker 错误图标/计数

javascript - NextJS 自定义 404 页面未显示

javascript - 映射函数返回带有索引而不是字符串值的数组

javascript - 是否可以将 promise 包装在生成器中?

javascript - Babili 缩小但不转译

javascript - 如何在 Chrome 浏览器控制台中提交包含输入值的表单?

css - 当我的 css 中没有列出宽度和高度的计算样式时,它们来自哪里

javascript - 如何从下到上迭代子元素

javascript - 我们如何从 JS block 中读取 R 变量?

javascript - 来自 CodeBehind 的 ASP.NET 警报换行符