为何第二个函数未启用"use strict"模式?控制台显示window对象
"use strict" Doesn't Affect Your test2 Function? Great question! Let's break down exactly why this happens—it all boils down to function hoisting and how JavaScript parses strict mode directives.
Core Issue Explained:
Function declarations get hoisted
JavaScript moves all function declarations to the top of their containing scope during the parsing phase—before any code runs. Even though you wrotetest2after the global"use strict"line, the parser processestest2's declaration first, way before it hits the strict mode directive.Strict mode is a parsing-time directive
Strict mode isn't a runtime toggle—it tells the parser to treat subsequent code as strict. Sincetest2was parsed before the global"use strict"was encountered, the parser never applies strict mode rules totest2's body. That's why callingtest2()still logs the globalwindowobject (non-strict behavior) instead ofundefined.
Why Putting "use strict" Inside test2 Works:
When you move the strict mode directive inside test2, the parser hits that directive as soon as it processes the function's body. This tells the parser to treat all code inside test2 as strict, so calling it results in this being undefined—exactly what you expect.
Fix for Global Strict Mode:
To make global strict mode apply to test2, place "use strict" at the very top of your global scope, before any function declarations:
"use strict"; // Applies to all subsequent code function test() { console.log(this); } test(); // Logs undefined (strict mode behavior) function test2() { console.log(this); } test2(); // Also logs undefined, as expected
Key Takeaway:
Strict mode directives only affect code parsed after the directive. Function hoisting can bypass this if your directives aren't placed at the start of the scope.
内容的提问来源于stack exchange,提问作者Avernikoz

