Im curious when it is needed/best practice to use the keyword this
. I understand that this
is used when determining a functions this
value
'This' is used inside a function and it contains the value of the object that invokes the function.
For example:
function a(){
this.newVariable = 'Phil';
}
a();
console.log(newVariable); //This line would display Phil
In this case, even though we just define newVariable inside the function a(). The object that invokes the function is the global object window, so 'this' points to window and this.newVariable is at the global scope.
Another example would be:
var c={
log:function(){
this.name = 'Phil';
}
}
In this case, 'this' points to the object c, since the log function will be invoked by c.
We have more tricky cases in the use of the object 'this' in Javascript. This is a good article to grasp the concept: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/