参考大佬地址:
严格模式的作用
-
消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
-
消除代码运行的一些不安全之处,保证代码运行的安全;
-
提高编译器效率,增加运行速度;
-
为未来新版本的Javascript做好铺垫。
注:经过测试 IE6,7,8,9 均不支持严格模式。
严格模式的使用限制 (es6下)
只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设定为严格模式
//参数默认值
function testFn(a, b = 1) {
'use strict';
// Illegal 'use strict' directive in function with non-simple parameter list
console.log(1)
}
// 这里的 non-simple parameter 指的就是形参有默认值了
//扩展运算符
function testFn1(...value) {
'use strict';
//Illegal 'use strict' directive in function with non-simple parameter list
console.log(1)
}
//解构
function testFn({ a, b }) {
'use strict';
}
两种方法可以规避这种限制。
第一种:设定全局性的严格模式,这是合法的。
'use strict';
function testFn({ a, b } = {}) {
// 因为严格模式下这种八进制写法是会报错的
// Octal literals are not allowed in strict mode
console.log(013)
}
testFn()
第二种:j将函数包裹在一个无参数的立即执行函数里面
const doSomething = (function() {
'use strict';
return function(value = 42) {
return value;
};
}());