【问题标题】:javascript: value of 'this' is different between debugger and actual resultjavascript:调试器和实际结果之间的“this”值不同
【发布时间】: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() 和一个下一步(相信我,这正是下一步),窗口对象正在打印到控制台。

【问题讨论】:

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


【解决方案1】:

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

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

基本上等价于

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

【讨论】:

  • @Kludge 在这方面,没有。它们就像从.bind() 返回的函数。
  • 然后浏览器调试器坏了。你用的是什么浏览器?
  • @Grundy 你这么认为没关系,但语言不同意 :)
  • @Creynders 这没有意义。在那一刻,在执行流程中,箭头函数中没有隐含的this 绑定,这意味着它沿着作用域链上升。
  • @Kludge No. 如果this 绑定很重要,则使用function。箭头函数对于您想要外部 this 的事情很有用,例如事件处理程序和从函数返回函数。它们并不是要替代 function
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 2012-11-07
  • 2020-09-17
  • 1970-01-01
相关资源
最近更新 更多