I am trying to understand internals of Javascript
. I have some misunderstanding of this
keyword.
Everywhere stated that this
keyword is reference to the object that invokes function.
But as far as I know function
is an object as well.
So consider this example
var car = {
brand: "Nissan",
getBrand: function(){
var closure = function(){
console.log(this.brand);
console.log(this);
};
return closure();
}
};
car.getBrand();
Why does this
reference inside closure
point to the global
object instead of getBrand
wrapping function ? Again everything is object in javascript, so I cannot understand this behavior.
Please explain this from internals perspective.
Thanks
Because value of this
is determined by how function
is called..closure
is called with no reference of context
and global context is window
(in Browser)
Use Function.prototype.call
to specify this
context while function is invoked
var car = {
brand: "Nissan",
getBrand: function() {
var closure = function() {
console.log(this.brand);
console.log(this);
};
return closure.call(this);
}
};
car.getBrand();