"use strict" 在程序中间

"use strict" in the middle of the program

为什么第二个函数没有使用 "use strict"; 模式(它告诉我 window 控制台中的对象):

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!

但是如果我在第二个函数的主体中定义严格模式,一切都会如我所料。

function test() {
    console.log(this);
}
test();   // will be global or window

function test2() {
"use strict";
    console.log(this);
}
test2();

我的问题很简单——为什么会这样?

因为 "use strict" 仅当它是当前 script/function 的第一个语句时才有效。来自 the MDN docs :

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

the MDN documentation:

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

在您的第一个代码块中,您有 "use strict"; 但它不是脚本中的 first 语句,因此它没有任何效果。

在你的第二个语句中,它是函数中的第一个语句,所以确实如此。