Menachem Hornbacher
Menachem Hornbacher

Reputation: 2166

Why is this the window object in a jQuery event handler?

I have a small on load script to set some classes that looks like this:

function frameIt() {
  console.log("called frameit")
  $( 'img' ).on('load', () => {
    console.log("running listener")
    debugger;
    $( this ).addClass( "tasty" );
  });
  console.log("set listener")
}

My issue is that $(this) is always set to the window even though this in the context is the loaded img tag as Chrome's debugger shows. Any ideas for why this is happening? Here's a Chrome debugger screenshot: enter image description here

Upvotes: 0

Views: 86

Answers (2)

Andrew Li
Andrew Li

Reputation: 57964

It's because arrow functions don't bind their own this context -- they take the this value of the enclosing scope. Since jQuery binds an event handler's this internally, but this cannot be bound to an arrow function, this refers to window as it is the this value of the enclosing scope. Use a regular function instead.

Upvotes: 6

Tung
Tung

Reputation: 21

$( 'img' ).on('load', function () {
    console.log("running listener")
    debugger;
    $( this ).addClass( "tasty" );
});

Upvotes: 2

Related Questions