When you set the value of this
to null
then it will always map to the global object (in non-strict mode).
Here just declaring an anonymous function and setting this
as null and calling it immediately by passing the property of the global object globalLet
will always return the global value.
Caution: This won't work in strict mode, where this
will point to null
.
var globalLet = "This is a global variable";
function fun() {
var globalLet = "This is a local variable";
globalLet = (function(name){return this[name]}).call(null, "globalLet");
console.log(globalLet); //want to print 'This is global variable' here.
}
fun();
According to the ES5 spec
15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, … ] ] ) # Ⓣ Ⓡ When the call method is called on an object func with argument
thisArg and optional arguments arg1, arg2 etc, the following steps are
taken:
If IsCallable(func) is false, then throw a TypeError exception.
Let argList be an empty List.
If this method was called with more than one argument then in left to
right order starting with arg1 append each argument as the last
element of argList
Return the result of calling the [[Call]] internal method of func,
providing thisArg as the this value and argList as the list of
arguments.
The length property of the call method is 1.
NOTE The thisArg value is passed without modification as the this
value. This is a change from Edition 3, where a undefined or null
thisArg is replaced with the global object and ToObject is applied to
all other values and that result is passed as the this value.