[英]What happens when you combine “use strict”; inside functions with “use strict”; in the global context?
<!DOCTYPE html>
<html>
<body>
<script>
function useStrict(){
"use strict";
}
"use strict";
foo=10;
alert(foo);
</script>
</body>
</html>
Leads to no error. 导致没有错误。 Conclusion: strict mode isn't activated.
结论:严格模式未激活。 But if I remove the function definition:
但是,如果我删除函数定义:
<!DOCTYPE html>
<html>
<body>
<script>
"use strict";
foo=10;
alert(foo);
</script>
</body>
</html>
I get an error. 我得到一个错误。 Conclusion: strict mode is activated.
结论:严格模式已激活。 But if I remove the
"use strict"
line in the global context and keep the function: 但是,如果我删除全局上下文中的
"use strict"
行并保留该功能:
<!DOCTYPE html>
<html>
<body>
<script>
function useStrict(){
"use strict";
}
foo=10;
alert(foo);
</script>
</body>
</html>
I get no error. 我没有错。 Conclusion: strict mode isn't activated.
结论:严格模式未激活。 What is going on here?
这里发生了什么?
It seems that when "use strict";
看来当
"use strict";
is both in the global context and in a function, they cancel out, since when I remove the function, strict mode is indeed activated. 在全局上下文和函数中都被取消,因为当我删除函数时,确实激活了严格模式。 But then, without the
"use strict";
但是随后,没有了
"use strict";
line in the global context, but inside of the function, strict mode isn't activated, which to me is unexpected. 全局上下文中的行,但在函数内部未激活严格模式,这对我来说是意外的。 How could they cancel out before if
"use strict";
如果
"use strict";
他们怎么能取消呢"use strict";
inside of a function call doesn't activate strict mode on its own? 函数调用内部不会自行激活严格模式吗?
Your first script, for context: 针对上下文的第一个脚本:
function useStrict() {
"use strict";
}
"use strict";
foo = 10;
alert(foo);
"use strict"
only has an effect at the top of a script. "use strict"
仅在脚本顶部起作用。 The function useStrict()
before it makes it not at the top. function useStrict()
使其不在顶部。 If you move it to the top, it will work. 如果将其移到顶部,它将起作用。
"use strict";
function useStrict() {
"use strict";
}
foo = 10;
alert(foo);
Otherwise it has the same semantics as "use mayonnaise"
. 否则,它与
"use mayonnaise"
具有相同的语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.