3

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

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

4

2 回答 2

3

请参阅MDN 文档

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

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

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

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

于 2018-03-20T14:54:16.990 回答
2

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

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

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

于 2018-03-20T14:54:07.823 回答