JavaScript : why ‘var self = this’
When I started JavaScript I used to see this code a lot of time and I always wondered why do I need to assign this to another variable and then use that (self in our case). Why can’t I just go ahead and use this keyword instead. After some google searches, I got my answer.
Now, ‘this’ is not a variable instead it is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping(in C open/close {} curly braces refers to a block). JavaScript has two scopes namely, global and local scope.
- local scope : variables declared within a function becomes local to that function
- global scope: variable defined outside of function becomes global and all scripts and functions can access it.
Let us consider the below example to see how scoping works


Here, obj.outerFunction() is a method invocation on ‘obj’ Object. So the context in outerFunction() refers to ‘obj’ and therefore Line No.3 evaluates to true. So far, ’this’ keyword is referring to the expected object. Now let us introduce an innerFunction within outerFunction() and see whats the context there.


So what happened here??
The innerFunction is within the ‘obj’ context but when I try to call the method once it is returned my context is lost and ‘this’ no longer refers to ‘obj’ but to global object and this is where the problem crops up.
Now to resolve this issue, we can save the object’s context to some other variable say ‘self’ and then we can use ‘self’ in innerFunction to refer to the object’s context. Thanks to closure in JavaScript, my innerFunction can refer outerFunction’s variable even after returning. Basically, it remembers the environment in which it was created though it has returned from the outerFunction.


I hope this would help. Feel free to add to it :)