开启严格模式的能够改变语法解析以及运行行为,旨在保证写出安全、健壮的代码。

‘use strict’的作用域

'use strict' 只能在全局作用域或者函数作用域(局部作用域)当中开启,在封闭大括弧内{ }无效。
全局作用域:所有的作用域都起作用;
函数作用域:只在该函数作用域及其子孙作用域起作用;

  1. var context = {}
  2. function strict1(str) {
  3. "use strict";
  4. function f(){
  5. with(context){console.log(str)}; // Uncaught SyntaxError: Strict mode code may not include a with statement
  6. }
  7. f(str);
  8. }
  9. function strict2(f, str) {
  10. "use strict";
  11. f(str);
  12. }
  13. function nonstrict(str) {
  14. with(context){console.log(str)};
  15. /*
  16. 由于js时静态作用域,所以该方法的上层作用域是全局作用域,在这里全局作用并没有开启严格模式,并不受影响,
  17. 而调用它的作用域strict2 虽然开启了严格模式,但也不受其影响
  18. */
  19. }

参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Strict_mode
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/eval