Daniel Kats
Daniel Kats

Reputation: 5554

JQuery overwriting this keyword in prototype

JQuery seems to overwrite the this keyword of my instance method, when added as an event handler. Why does this happen? Code below:

function Foo() {};
Foo.prototype.bark = function() {
    console.log(this);
};

var foo = new Foo();

$("#b").click(foo.bark);

Output on click: <button id="b" type="button">

However JQuery does not seem to override the this keyword in the code below:

$("#b").click(function() { foo.bark(); });

Output on click:

`Foo { bark=function()}`

Upvotes: 0

Views: 128

Answers (4)

stefanz
stefanz

Reputation: 1326

The solution for your problem is $.proxy(). You can read more about it here

Try $('#b').on('click', $.proxy( foo.bark, this ) )

Edit : actually the correct call of proxy function is $.proxy( foo.bark, foo );

Upvotes: -1

marekful
marekful

Reputation: 15351

This is the expected behaviour. All functions that are assigned as an event listener will have this pointing to the element instance on which the event was fired.

You can overcome this by using an anonymous wrapper function as you handler like:

$("#b").click(function() {foo.bark() }); 

Upvotes: 5

Evan Davis
Evan Davis

Reputation: 36592

From the docs:

The handler parameter takes a callback function... Within the handler, the keyword this refers to the DOM element to which the handler is bound.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

That is because click passes reference to the element to it's handler (which is bark in your case)

When you do this :

$("#b").click(function(){
  foo.bark();
});

You will not be able to use this to reference clicked element in bark()

Upvotes: 2

Related Questions