程序中间写上"use strict"是什么意思?

4

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

我的问题很简单——为什么会发生这种情况?

1
为了生效,"use strict"; 必须位于代码块或函数的最顶部。如果它之前有任何代码,则不起作用。 - Pointy
2个回答

3
请参见MDN文档:严格模式

要在整个脚本中启用严格模式,请在任何其他语句之前放置精确语句"use strict";(或'use strict';)。

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

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

在您的第二个代码块中,它是函数中的第一条语句,因此有效。


类似这样的代码 function myFunc(){} 'use strict'; function myOtherFunc() { // my first expressions } 可以工作吗? - messerbill

2

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接