M H*_*her 0 javascript jquery arrow-functions
我有一个小的加载脚本来设置一些看起来像这样的类:
function frameIt() {
console.log("called frameit")
$( 'img' ).on('load', () => {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
console.log("set listener")
}
Run Code Online (Sandbox Code Playgroud)
我的问题是$(this)始终设置为window即使this在上下文中是imgChrome的调试器显示的加载标记.为什么会发生这种情况的任何想法?这是一个Chrome调试器截图:

这是因为箭头函数不绑定它们自己的this上下文 - 它们采用this封闭范围的值.由于jQuery的结合事件处理程序是this在内部,但this不能被绑定到一个箭头功能,this指的是window因为它是this封闭的范围值.请改用常规功能.