This :
‘This’ keyword refers to the object from where it was called.
The value of “this” keyword will always depend on the object that is invoking the function.
Ex :1
var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}
}
obj.getName();
In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.
Ex :2
var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}
}
var getName = obj.getName;
var obj2 = {name:"akshay", getName };
obj2.getName();
Can you guess the output here?
The output will be “akshay”.
Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .
The silly way to understanding the this keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot .
If there is no object before the dot like in example1, the value of this keyword will be the global object.