Understanding the 'this' keyword in Javascript .

Understanding this took me quite some time and the way I learn is by reading source code and then interpreting what I get from them.I write so that I don't forget it later on. This Post I will try to explain how the awesome keyword 'this' works in javascript as it has different meaning at different places.
Before starting I would like you to remember the key rule :
'this' always refers to the owner.So,here are instances that Prove the above line.This is different is different circumstance.
Below are different situations in which this can be used ..
When function is called as a function.
Example :
function check (){
return this;}
assert(check()==windows, "this point to the window') ;
Here this will point to the window object .
When called as a method
When a method is called 'this' refer to the object on which it was called.Using the previous function check in this example
var o ={fn:check};
//here we add a property to the object o that is a method of it .
//Now
assert(o.fn==o, this is pointing to the o object now) ;
When called as constructor
Constructor in javascript have all the dark magic involved. When ever a constructor is called a new object is created and that object is passed as this in the function parameter.To understand this lets have a look at this example.
function bird(){
this.wings=function(){return this;};
}
pelican =new bird();
assert(pelican.wings==pelican, "This refer to the object pelican" );
Here the newly created object pelican is passes to the constructor as this .
Here the newly created object pelican is passes to the constructor as this .
SUMMARY:
For methods, it’s the method’s owning object; for top-level functions, it’s always window (or it may be said as the method of window object),for constructor its the newly created object instance.
But wait here this was done all implicitly, what if I wanted to define the context of this as I require? Yes this can be done using the apply(), and call() methods of every function .
With The apply()/call() methods.
The apply() function is a method of all the functions , being a first class object functions can have properties , methods etc. When called using apply() it is passed two parameter the context and an array or arguments , the call() is also similar to this but instead of an array all the arguments are passed comma separated. Here is the example .
function add(){
sum=0;
for (var i=0;i<arguments.length;i++)
sum +=arguments[i];
this.sum =sum;
}
var first={};
var second={};
add.apply(first, [1,2,3,4,5]);
add.call(first,1,2,3,4);
assert(first.sum==15,"This used a apply");
assert(second.sum==10,"This used a call");
I don't think i need to explain this bit of code , here we make the first argument the context and this use the function as if it was a method of that object.
I have tried to explain to the best of my knowledge,I might be wrong at some point (i don't think i am though) , everyone is welcomed .

0 comments