window
is the default value for this
if you run your code in a browser. As noted in the comments below, this
will be undefined if 'use strict';
is in effect.
the value of this
changes on the basis of the object where it resides.
example:
1
var test = {
a: 1,
b: function () {
console.log(this.a)
}
}
In this case the value of this
will be the containing object.
var test = {
a: 1,
b: function () {
setTimeout(function () {console.log('surprise', this.a)}, 0)
}
}
This piece of code however doesn't give the same result.
Here without strict mode on, on a browser, property a
will be accessed over the window
.
The reason being the function in the setTimeout doesn't have the access to the object.
2
var someObject = {
value: 1,
someFunction () {
return function () {
console.log(this.value)
}
}
}
var displayValue = someObject.someFunction()
displayValue()
In this case too, this
is undefined, as the value of this
changes with respect to the object which contains the function being called.
someFunction
is a method on the object someObject
therefore, the value of this
inside would be equal to someObject
but the function returned by someFunction
is not called by someObject
hence the difference.