Why the second function didn't use the "use strict"; mode (it shows me window object in console):
function test() {
console.log(this);
}
test(); // will be global or window, it's okay
"use strict";
function test2() {
console.log(this);
}
test2(); // will be global, BUT WHY? It must be undefined, because I have used strict mode!
But if I define strict mode in the body of the second function, all will be as I expect.
function test() {
console.log(this);
}
test(); // will be global or window
function test2() {
"use strict";
console.log(this);
}
test2();
My question is simple — why it happens?
See the MDN documentation:
and
In your first code block, you have
"use strict";but it isn't the first statement in the script, so it has no effect.In your second, it is the first statement in a function, so it does.