【问题标题】:fat arrow function not working with jquery getJSON?胖箭头函数不适用于 jquery getJSON?
【发布时间】:2016-06-14 08:53:50
【问题描述】:

我正在尝试使用新的 => 表示法将回调绑定到 jQuery getJSON 命令,但它不起作用。

旧代码(工作)

$.getJSON("js/questions.json", function(data){
   console.log("loaded json but lost my scope...");
});

胖箭头(不工作)

$.getJSON("js/questions.json", (data) => this.test);
function test(data){
     console.log("If we get here we might still have our scope");
}

【问题讨论】:

  • 第二个示例中的 this 引用是什么?
  • $.getJSON("js/questions.json", test);$.getJSON("js/questions.json", (data) => test(data));
  • 为什么你认为你需要第二个this.test 上的this.
  • 感谢@PranavCBalan,这就是答案!我只是忘记在函数调用中添加 ().... 对于其他人:我需要“this”来引用调用此代码的对象。它不在全局窗口范围内。我应该发布完整的代码来澄清这一点。

标签: jquery ecmascript-6


【解决方案1】:

您的箭头函数中唯一的问题是this 只需将其删除并同时传递数据。

$.getJSON("js/questions.json", (data) => test(data));

或者不需要匿名函数,只需将函数引用设置为第二个参数。

$.getJSON("js/questions.json", test);

【讨论】:

  • 这两者之间有很大的不同。 :-) 但绝对是,this.test 上的 this. 是问题所在。
  • 第一个例子就是答案,虽然我确实需要'this'。我的函数不是从全局窗口范围调用的。我应该发布完整的代码来澄清这一点。所以工作代码是 (data) => this.test.bind(this,data);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 2018-02-01
  • 1970-01-01
  • 2018-01-29
  • 2023-02-10
相关资源
最近更新 更多