【发布时间】: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