启用JavaScript严格模式编程可以避免代码在执行过程中出现意想不到的结果,JavaScript是一种向后兼容的语言,所以为了消除JS中一些不严谨不安全的语法,减少怪异行为的出现,在严格模式下编程是很有必要的。
启用严格模式的方法很简单,只需要在脚本顶部添加'use strict';
即可,也可以只在函数中使用,只需在函数体的顶部添加'use strict';
,对于不支持严格模式的浏览器会把它当做普通字符串。
现代浏览器都支持严格模式,包括IE10+。
变量
- 不允许意外创建全局变量
'use strict';
bar = 1; // bar is not defined
- 不能对变量调用delete操作符
'use strict';
var bar = 1;
delete bar; // Delete of an unqualified identifier in strict mode.
对象
- 不能为只读对象赋值
'use strict';
var people = {name: 'wmui'};
Object.defineProperty(people, 'name', {
writable: false
})
people.name = '三竹' // Cannot assign to read only property 'name' of object
- 不能为不可配置对象使用delete操作
cript>
'use strict';
var people = {name: 'wmui'};
Object.defineProperty(people, 'name', {
configurable: false
})
delete people.name // Cannot delete property 'name'
函数
- 修改形参不会反映到arguments中
use strict';
function foo(num) {
num = num + 1;
return arguments[0];
}
foo(3)
// 严格模式返回 3
// 非严格模式返回 4
- 不允许使用arguments.callee和arguments.caller
'use strict';
function fn(n){
return (n < 1) ? 1 : arguments.callee(n - 1);
}
fn(3);
// 严格模式 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
// 非严格模式 1
arguments.caller已废弃,现代浏览器不再支持
不允许使用eval()方法在包含上下文中创建变量或函数
"use strict";
function fn(){
eval("var x = 10");
return x
}
fn();
// 严格模式: x is not defined
// 非严格模式:10
下面这种方法允许使用:
"use strict";
function fn(){
var r = eval("var x = 10, y = 11; x+y");
return r
}
fn(); // 21
函数中this值为undefuned
"use strict";
var color = "red";
function fn(){
return this.color;
}
fn();
// 严格模式 Cannot read property 'color' of undefined
// 非严格模式 red
不能使用with()语句
'use strict';
with(location) {
alert(href)
}
// 严格模式 Strict mode code may not include a with statement
// 非严格模式 url地址
不允许八进制字面量
"use strict";
var value = 010;
// Octal literals are not allowed in strict mode.