gpt4 book ai didi

javascript - "use strict"在程序中间

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:05 25 4
gpt4 key购买 nike

为什么第二个函数没有使用"use strict"; 模式(它在控制台中显示我的窗口对象):

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();

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

最佳答案

参见 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"; 但它不是脚本中的第一个 语句,因此它没有任何效果。

在您的第二个语句中,它是函数中的第一条语句,确实如此。

关于javascript - "use strict"在程序中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com