Reputation: 5554
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
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
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
Reputation: 36592
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
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