为什么这是 jQuery 事件处理程序中的 window 对象?
Why is this the window object in a jQuery event handler?
我有一个小的加载脚本来设置一些 类,看起来像这样:
function frameIt() {
console.log("called frameit")
$( 'img' ).on('load', () => {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
console.log("set listener")
}
我的问题是 $(this)
始终设置为 window
,即使上下文中的 this
是作为 Chrome 加载的 img
标签' s 调试器显示。为什么会发生这种情况的任何想法?这是 Chrome 调试器屏幕截图:
这是因为箭头函数不绑定它们自己的 this
上下文——它们采用封闭范围的 this
值。由于 jQuery 在内部绑定事件处理程序的 this
,但 this
不能绑定到箭头函数,因此 this
指的是 window
因为它是 this
封闭范围的值。请改用常规函数。
$( 'img' ).on('load', function () {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
我有一个小的加载脚本来设置一些 类,看起来像这样:
function frameIt() {
console.log("called frameit")
$( 'img' ).on('load', () => {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});
console.log("set listener")
}
我的问题是 $(this)
始终设置为 window
,即使上下文中的 this
是作为 Chrome 加载的 img
标签' s 调试器显示。为什么会发生这种情况的任何想法?这是 Chrome 调试器屏幕截图:
这是因为箭头函数不绑定它们自己的 this
上下文——它们采用封闭范围的 this
值。由于 jQuery 在内部绑定事件处理程序的 this
,但 this
不能绑定到箭头函数,因此 this
指的是 window
因为它是 this
封闭范围的值。请改用常规函数。
$( 'img' ).on('load', function () {
console.log("running listener")
debugger;
$( this ).addClass( "tasty" );
});