ECMAscript 5添加了第二种支行模式:严格模式(strict mode)。
- 针对单个脚本
<script>
"use strict";
console.log("这是严格模式。");
</script>
- 针对单个函数
function strict(){
"use strict";
return "这是严格模式。";
}
function notStrict() {
return "这是正常模式。";
}
- 全局变量显示声明
在正常模式中,如果一个变量没有声明就赋值,默认是全局变量。严格模式禁止这种用法,全局变量必须声明。
"use strict";
v = 1; // 报错,v未声明
for(i = 0; i < 2; i++) { // 报错,i未声明
}
- 禁止this关键字指向全局对象
function f(){
return !this;
}
// 返回false,因为"this"指向全局对象,"!this"就是false
function f(){
"use strict";
return !this;
}
// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。
- 禁止删除变量
严格模式下无法删除变量,只有configurable设置为true的对象属性,才能删除 。
"use strict";
var x;
delete x; // 语法错误
var o = Object.create(null, {'x': {
value: 1,
configurable: true
}});
delete o.x; // 删除成功
- 函数不能有重名的参数
正常模式下,如果函数有多个重名的参数,可以用arguments[i]读取,严格模式下,这属于语法错误。
"use strict";
function f(a, a, b) { // 语法错误
return ;
}
最后欢迎大家访问我的个人网站:1024s