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 表示八进制数,否则报错 在严格模式下,八进制字面量必须以 0o0O 为前缀,不能使用前缀 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: ...

总结

  1. 变量必须声明后再使用
  2. 函数不能有同名属性
  3. 不能使用with语句
  4. 不能对只读属性赋值
  5. 不能使用前缀0表示八进制树
  6. 不能删除不可删除的属性
  7. 不能删除变量
  8. eval不会在它的外层作用域引入变量
  9. eval和arguments不能被重新赋值
  10. arguments不会自动反映函数参数的变化
  11. 不能使用arguments.callee
  12. 不能使用arguments.caller
  13. 禁止this指向全局对象
  14. 不能使用fn.caller和fn.arguments获取函数调用的堆栈
  15. 增加了保留字(比如protectedstaticinterface