Strict Mode

Strict Mode

作用

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. 这种严格的上下文能够禁掉一些行为以及抛出更多地错误.

为什么需要它

Strict mode makes it easier to write “secure” JavaScript.

如何开启

  • 文件顶部:
// File: myscript.js

'use strict';
var a = 2;
...
  • function 顶部:
function doSomething() {
    'use strict';
    ...
}

约束

  • 禁止全局变量
'use strict';

// Assignment to a non-writable global
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError
  • delete 不可删除的属性,会抛出异常。例如尝试 delete Object.prototype
'use strict';
delete Object.prototype; // throws a TypeError
  • object literal 中的所有属性名称应该是唯一的。反例 var x = { "x1": 1, "x1": 2 }
'use strict';
var o = { p: 1, p: 2 }; // !!! syntax error
  • 函数参数的名字必须唯一。反例 function sum(x, x) {}
function sum(a, a, c) { // !!! syntax error
  'use strict';
  return a + a + c; // wrong if this code ran
}
  • 禁用八进制声明 var x = 023
'use strict';
var sum = 015 + // !!! syntax error
          197 +
          142;
  • 禁用 with
'use strict';
var x = 17;
with (obj) { // !!! syntax error
  // If this weren't strict mode, would this be var x, or
  // would it instead be obj.x?  It's impossible in general
  // to say without running the code, so the name can't be
  // optimized.
  x;
}
  • eval 不会产生新的变量
  • 禁止 delete 普通变量。反例 delete x
'use strict';

var x;
delete x; // !!! syntax error
  • Forbids binding or assignment of the names eval and arguments in any form
  • Strict mode does not alias properties of the arguments object with the formal parameters. (i.e. in function sum (a,b) { return arguments[0] + b;} This works because arguments[0] is bound to a and so on. )
  • 不支持 arguments.callee
'use strict';
function fun(a, b) {
  'use strict';
  var v = 12;
  return arguments.caller; // throws a TypeError
}
fun(1, 2); // doesn't expose v (or a or b)

function restricted() {
  'use strict';
  restricted.caller;    // throws a TypeError
  restricted.arguments; // throws a TypeError
}

参考