Alex
Alex

Reputation: 5724

Declaring this as something else

I've seen a few examples of this lately, and am rather curious why it happens. ( For example in the extjs source code, its all over the place )

var me=this;

or

var that=this;

And instead of referring to this, me is used.

Upvotes: 0

Views: 60

Answers (4)

Ankur
Ankur

Reputation: 33637

This is usually done in case of a closure which need to access "this" when the closure was created.

For ex:

var obj = 
{
   name: "Hello",
   init : function() {
      var me = this;
      $("#txt").click ( function() {
         alert(me.name);
      });
   }
}

In the above example the init function in obj attaches an event handler to some txt element click event. This event handler needs to access the name property of obj object. Now inside the event handler the "this" will point to some other object (element on which event happens) and not to obj object. Hence we create a variable called me this points to this (obj) and this me is used inside the event handler to refer to obj.

Upvotes: 1

user837324
user837324

Reputation:

There's a pretty thorough explanation here:

http://bonsaiden.github.com/JavaScript-Garden/#function.this

Upvotes: 0

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

This is required to be able to access the "parent" object when working with closures. To put simply, this inside an anonymous function always points to window, so this pattern is used to work around it, allowing accessing the original object.

http://jibbering.com/faq/notes/closures/ is a rather in-depth explanation of how closures work.

Upvotes: 1

People does it to save the this pointer to a local variable. Then whenever the thiscontext changes they refere back to that (or me)

Upvotes: 1

Related Questions