Javascript: this, that, self

Often one comes across javascript codes like the following:

var that = this;


var self = this;
The above code usage is due to 2 features of Javascript:
  1. binding is always explicit.  For example, if you don’t explicit bind a variable to an object, Javascript may look for the variable in window object.
  2. Keyword this loses the binding/context when you are accessing a method through a reference.

The solution is to leverage “closures”, letting code instead of a block access variables/methods declared in scopes surrounding that code block.

processItems: function() {
var that = this;
this.items.each(function(item) {
// Process item





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s