I am trying to understand the this
keyword on Javascript.
I was doing some tests on chrome console and I came across two different results that I was expecting to be the same:
var myTest = {};
myTest.test1 = function() {
return this; // this = Object
}
This first function returns myTest
object which I understand.
var myTest = {};
myTest.test1 = function() {
return function test2() {
return this; // this = Window
}
}
Why is the second function returning the window instead of the myTest
object?
Thank you
this
refers to the current object on which the function is called. When you calledtest1
, you would have done like thisNow,
test1
is called onmyTest
object. That is whythis
refers tomyTest
in the first case.In the second case, you would have executed like this
myTest.test1()
returns a function and you are invoking without any current object. In that case, JavaScript will make sure thatthis
will refer the global object (window
in this case).Note: But, in strict mode,
this
will beundefined
, in the second case. You can confirm that like thisOutput will be
But if you include
use strict
like thisOutput will be