JavaScript严格模式的规则和差异
规则
变量必须声明后再使用
"use strict";
x = 10; // ReferenceError: x is not defined
函数不能有同名属性
"use strict";
function foo(a, a) { // SyntaxError:...
}
不能使用with语句
"use strict";
with (Math) { // SyntaxError:...
x = cos(2);
}
不能对只读属性赋值
const obj = {};
Object.defineProperty(obj, "x", { value: 42, writable: false });
obj.x = 9; // TypeError: ...
不能使用前缀 0 表示八进制数,否则报错
在严格模式下,八进制字面量必须以 0o
或 0O
为前缀,不能使用前缀 0。
"use strict";
const num = 010; // SyntaxError: Octal literals are not allowed in strict mode.
不能删除不可删除的属性,否则报错
"use strict";
delete Object.prototype; // TypeError: ...
不能删除变量 delete prop,只能删除属性 delete global[prop]
"use strict"
var x = 1;
delete x; // SyntaxError:...
var obj = { y: 1 };
delete obj.y; // true
eval 不会在它的外层作用域引入变量
"use strict";
eval("var x = 2");
console.log(x); // ReferenceError: x is not defined
eval 和 arguments 不能被重新赋值
"use strict";
eval = 42; // SyntaxError: ...
arguments = 42; // SyntaxError: ...
arguments 不会自动反映函数参数的变化
"use strict";
function foo(a) {
a = 42;
return [a, arguments[0]];
}
console.log(foo(1)); // [42, 1]
不能使用 arguments.callee
"use strict";
function foo() {
console.log(arguments.callee);
}
不能使用 arguments.caller
"use strict";
function foo() {
console.log(arguments.caller); // TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
}
禁止 this 指向全局对象
"use strict";
function foo() {
console.log(this); // undefined
}
foo();
不能使用 fn.caller 和 fn.arguments 获取函数调用的堆栈
"use strict";
function foo() {
console.log(foo.caller); // TypeError:...
}
foo();
增加了保留字 严格模式下,一些新的保留字如 protected、static 和 interface 被引入。
"use strict";
var protected = 1; // SyntaxError: ...
总结
- 变量必须声明后再使用
- 函数不能有同名属性
- 不能使用with语句
- 不能对只读属性赋值
- 不能使用前缀0表示八进制树
- 不能删除不可删除的属性
- 不能删除变量
- eval不会在它的外层作用域引入变量
- eval和arguments不能被重新赋值
- arguments不会自动反映函数参数的变化
- 不能使用arguments.callee
- 不能使用arguments.caller
- 禁止
this
指向全局对象 - 不能使用fn.caller和fn.arguments获取函数调用的堆栈
- 增加了保留字(比如
protected
、static
和interface
)