Reputation: 173
function foo() {
console.log(this.a);
}
var a = 2;
(function() {
"use strict";
foo(); // 2
})();
I was just wondering, how come calling foo()
still gives the value 2? I thought that since foo
is called inside of an IIFE then this.a
would evaluate to undefined
, since there is no a
variable in the IIFE.
Upvotes: 7
Views: 242
Reputation: 4217
that is because both foo
and a
are declared in the global scope that is they are properties of the global object window
.
the this
inside IIFE itself will be undefined
because it is in strict
mode. but calling foo
inside the IIFE will make this
inside the foo
refer to the window
object.
and since you already have a
in window
it get printed out.
Upvotes: 3
Reputation: 8316
Let's see two things here :-
Firstly your strict mode can apply to globalThis
when it's declared in that scope, like so :-
"use strict";
function foo() {
console.log(this.a);
}
var a = 2;
(function() {
foo(); // Throws error since this is undefined
})();
Another way could be how @Nick proposed it to run only foo
in strict mode.
Now secondly,
The this
inside your IIFE is your globalThis
which is window
for browsers. Variables declared with var
in global scope attach themselves to window
.
Upvotes: 2
Reputation: 50814
The "use strict" is being applied to the IIFE, not the foo()
function. As a result, foo
gets ran in sloppy mode/non-strict mode. Since foo()
doesn't get an explicit this
bound to it, it defaults to the global object, which in browsers is the window
. When you declare var a
in the global scope, it gets added to the window object as a property, meaning using this.a
inside of foo will give you the value held in a
, as it's accessing the a
property of the window
.
You would get undefined
for this
if foo() was being run in strict mode, not the IIFE:
function foo() {
"use strict";
console.log(this); // undefined
console.log(this.a); // Crash
}
var a = 2;
(function() {
foo();
})();
Upvotes: 7
Reputation: 1789
function test(){
return {
a: 9999,
testFunc: foo
}
}
function foo() {
console.log(this) //this is actually another context which point to its parent.
console.log(this.a);
}
var a = 2;
(function() {
"use strict";
console.log(this) //because of 'use strict', this will lead to undefined
foo(); // 2
test().testFunc(); //9999
})();
Upvotes: 1