【问题标题】:"use strict" in the middle of the program在程序中间“使用严格”
【发布时间】:2018-08-29 10:55:43
【问题描述】:

为什么第二个函数没有使用 "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();

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

【问题讨论】:

  • 为了产生效果,"use strict"; 必须位于代码块或函数的最顶部。如果它之前有任何代码,它什么也不做。

标签: javascript strict use-strict


【解决方案1】:

the MDN documentation:

要为整个脚本调用严格模式,请输入确切的语句“use strict”; (或“使用严格”;)在任何其他语句之前。

同样,要为函数调用严格模式,请输入确切的语句“use strict”; (或'use strict';)在任何其他语句之前的函数体中。

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

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

【讨论】:

  • function myFunc(){} 'use strict'; function myOtherFunc() { // my first expressions } 这样的东西会起作用吗?
【解决方案2】:

因为"use strict" 仅在它是当前脚本/函数的第一条语句时才有效。来自the MDN docs

要为整个脚本调用严格模式,请将确切的语句 "use strict";(或 'use strict';放在任何其他语句之前

同样,要为函数调用严格模式,请将确切的语句 "use strict";(或 'use strict';)放在函数体中在任何其他语句之前。

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 2021-10-04
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多