n1313 n1313 - 25 days ago 15
Javascript Question

How to create proper closures in jQuery?

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?

CMS CMS
Answer

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 this keyword represents the DOM element.

For getting "bar" you should store a reference to the outer closure:

var bar = function() {
  var self = this;

  this.baz = function() {
    this.input = $('.input');
    this.input.bind("keydown keyup focus blur change", this.foo);
  }

  this.foo = function(event){
    console.log(this); // the input
    console.log(self); // the bar scope
  }
};

Note: If the bar function is called without the new operator, this will be the window object and baz and foo will become global variables, be carefull!

However I think your code can be simplified:

var bar = {
  baz: function() {
    var input = $('.input');
    input.bind("keydown keyup focus blur change", this.foo);
  },

  foo: function(event){
    console.log(this); // the input
    console.log(bar); // reference to the bar object
  }
};
Comments