Sean Coleman
Sean Coleman

Reputation: 103

Understanding bind(this) inside jquery bind function

I see a lot of the following code in well written jquery code and I have searched all over the web trying to find an answer.

$(document).bind('someEvent',function(arg1) {
   this.something
}.bind(this));

What is the purpose of the .bind right after the function declaration inside the initial bind call? It would really help if a simple example could be written showing the difference visually with and without the nested bind.

I know it has something to do with global versus local scope I think.

Thanks so much

Sean

Upvotes: 2

Views: 1271

Answers (1)

Travis J
Travis J

Reputation: 82267

jQuery's bind is simply a way to attach an event handler. For example, these two are essentially the same

$(document).click(function(){});
$(document).bind('click',function(){});

Bind was originally used instead of the now preferred method of on (as of version 1.7).

Javascript's bind is a way to attach a lexical environment to a function. Essentially it overwrites this to be the passed context. These two are equivalent

var self = this;
$(document).click(function(){
 console.log(self);
});

and

$(document).click(function(){
 console.log(this);
}.bind(this));

Upvotes: 1

Related Questions