You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何第二个函数未启用"use strict"模式?控制台显示window对象

Why Global "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:

  1. 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 wrote test2 after the global "use strict" line, the parser processes test2's declaration first, way before it hits the strict mode directive.

  2. Strict mode is a parsing-time directive
    Strict mode isn't a runtime toggle—it tells the parser to treat subsequent code as strict. Since test2 was parsed before the global "use strict" was encountered, the parser never applies strict mode rules to test2's body. That's why calling test2() still logs the global window object (non-strict behavior) instead of undefined.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:05:27