严格模式
在 ECMAScript5 标准中,JavaScript 提出了严格模式的概念:
具有限制性的 JavaScript 模式,使代码隐式脱离了"懒散模式"
支持严格模式的浏览器在检测到代码中有严格模式时,会以更加严格的方式对代码进行检测和执行
支持在 js 文件中开启严格模式,也支持对某一个函数开启严格模式
使用"use strict" 开启严格模式
1. 无法意外的创建全局变量
//开启严格模式
'use strict';
// 禁止意外创建全局变量
global = '意外创建的全局变量';
console.log(global); // Uncaught ReferenceError: message is not defined
function foo() {
age = 20;
console.log(age);
}
foo(); // ReferenceError: age is not defined
2. 静默失败的赋值操作报出错误异常
//开启严格模式,直接报错
'use strict';
const value = 100; //(定义常量)
value = 1.14; //重新赋值(为变量)
console.log(value); // Uncaught TypeError: Assignment to constant variable.
3. 禁止删除不可删除的属性
// 开启严格模式
'use strict';
// 对变量使用delete关键字
var value = 100;
// 非严格模式下:此处为静默失败,既没有报错也没有删除变量
delete value; // Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.
console.log(value); //100
// 严格模式下对数组和对方法属性使用delete关键字,效果不变
// 1、严格模式下删除数组内容
var arr = [1, 2, 3];
delete arr[0];
console.log(arr); //[empty, 2, 3]
// 2、严格模式下delete函数的属性
var obj = {
name: 'name',
};
delete obj.name;
console.log(obj.name); // undefined
4. 不允许函数参数有相同的名称
5. 不允许 0 的八进制语法
// 开启严格模式
'use strict';
// 不允许使用原先的八进制格式
var num1 = 0111; // 73
console.log(num1); // SyntaxError: Octal literals are not allowed in strict mode.
var num2 = 0o123; // 八进制
var num3 = 0x123; // 十六进制
var num4 = 0b100; // 二进制
console.log(num2, num3, num4); // 83 291 4
6. 不允许使用 with
// 开启严格模式
'use strict';
var message = 'hello world';
var obj = { name: 'jam', age: 20 };
function foo() {
// with语句可以形成自己的作用域,在with语句中打印age时,会输出obj对象中的age属性,但在with语句中打印不存在的属性message时,会向外层的作用域一层一层去查找
with (obj) {
console.log(age);
console.log(message);
}
console.log(message);
}
foo(); // SyntaxError: Strict mode code may not include a with statement
7. eval 不再为上层引用变量
// 开启严格模式
'use strict';
var jsString = "var message = 'hello world';console.log(message)";
eval(jsString); // 输出 hello world
console.log(message); // Uncaught ReferenceError: message is not defined
// 使用闭包或new Function,可以避开严格模式
function test1() {
return function () {
var testData = 'var msg = "it is test fn";console.log(msg)';
eval(testData);
};
}
function test2() {
// 开启严格模式,则再度禁止eval
var data =
'"use strict";var jsString = \'var message="hello world"\';eval(jsString);console.log("%c%s", "color: red", "message:", message);';
return new Function(data);
}
test1()(); // it is test fn
test2()(); // Uncaught ReferenceError: message is not defined
8. this 绑定不会默认转成对象
// 开启严格模式
'use strict';
// 严格模式下,执行函数(默认绑定)会指向 undefined ,非严格模式下会指向 window
function foo() {
console.log(this);
}
foo(); // undefined