严格模式
JavaScript 的严格模式是使用受限制的 JavaScript 的一种方式,从而隐式地退出“草率模式”。严格模式不仅仅是一个子集:这种模式有意地与普通情形下的代码有所区别。(MDN)
严格模式为 JavaScript 提供了一个更严格的运行环境。
开启严格模式后,部分特性会发生改变,如 this 指向 window 的函数不再指向 window,而是变成了 undefined。
function Test() {
'use strict';
console.log('this:', this);
}
Test(); // 输出:this: undefined
代码块
预览
复制
1. 开启严格模式
1.1 对单个 script 标签或者 js 文件开启严格模式
单个 js 文件或者 script 标签的严格模式,可以通过在所有代码执行前加上 'use strict' 字符串开启。
'use strict';
function Test() {
console.log('this:', this);
}
Test(); // 输出:this: undefined
代码块
预览
复制
图片描述
1.2 对一个函数开启严格模式
在函数顶端协商 'use strict' 字符串,就可以打开整个函数的严格模式。
function testWith() {
'use strict';
var person = {
name: '鸽子天王',
age: 12,
};
var age = 11;
with (person) {
console.log(name);
console.log(age);
}
}
testWith();
代码块
预览
复制
在严格模式下是不提供 with 语句的调用的,所以这里会爆 Strict mode code may not include a with statement 错误。
2