开启严格模式的能够改变语法解析以及运行行为,旨在保证写出安全、健壮的代码。
‘use strict’的作用域
'use strict'
只能在全局作用域或者函数作用域(局部作用域)当中开启,在封闭大括弧内{ }
无效。
全局作用域:所有的作用域都起作用;
函数作用域:只在该函数作用域及其子孙作用域起作用;
var context = {}
function strict1(str) {
"use strict";
function f(){
with(context){console.log(str)}; // Uncaught SyntaxError: Strict mode code may not include a with statement
}
f(str);
}
function strict2(f, str) {
"use strict";
f(str);
}
function nonstrict(str) {
with(context){console.log(str)};
/*
由于js时静态作用域,所以该方法的上层作用域是全局作用域,在这里全局作用并没有开启严格模式,并不受影响,
而调用它的作用域strict2 虽然开启了严格模式,但也不受其影响
*/
}
参考
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