This is an example of my code:
var bar = function() {
this.baz = function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change", this.foo);
}
this.foo = function(event){
console.log(this);
}
}
Clicking on my input gives me the input in the console, obviously. How can i get bar as this instead?
That happens because when you bind an event, the event handler function is called with the context of the DOM element which triggered the event, the
thiskeyword represents the DOM element.For getting “bar” you should store a reference to the outer closure:
Note: If the bar function is called without the
newoperator,thiswill be the window object andbazandfoowill become global variables, be carefull!However I think your code can be simplified: