### 1.Strict Mode简介 Strict Mode是ECMAScript 5中引入的新特性。使得ECMAScript 5在向后兼容ECMAScript 3的同时,允许显式地声明不兼容ECMAScript 3中Deprecated的语法。 ### 2.使用Strict Mode: 有两种方式来声明使用Strict Mode: 1.在Script开头声明全局使用Strict Mode
"use strict"; // your code here ...
2.在函数开头声明局部使用Strict Mode:
// non-strict code... function strictInside(){ "use strict"; // your code here... } // non-strict code...
3.最佳实践 在实践中,通常不使用全局的Strict Mode,因为在Script合并、压缩之后,Strict Mode会应用到所有Script,容易导致第三方的非Strict Mode脚本出错。所以通常采用局部Strict Mode:
// non-strict code... (function(){ "use strict"; // define your lib here. })(); // non-strict code...
### 3.Strict Mode中的限制 1.不能隐式的声明全局变量。
(function() { "use strict"; foo = "bar"; //Error //ReferenceError: foo is not defined })();
(function() { "use strict"; var foo = "test"; function bar(){} delete foo; // Error delete bar; // Error function test(arg) { delete arg; // Error } })(); //SyntaxError: Delete of an unqualified identifier in strict mode.
(function() { "use strict"; var foo = { bar: true, bar: false } //Error })(); //SyntaxError: Duplicate data property in object literal not allowed in strict mode
(function() { "use strict"; var eval = function() {}; // Error var arguments = ['foo', 'bar']; //Error })(); //SyntaxError: Variable name may not be eval or arguments in strict mode (function(eval, arguments) { "use strict"; })(); //SyntaxError: Parameter name eval or arguments is not allowed in strict mode
"use strict"; function foo(bar, bar) {} //Error //SyntaxError: Strict mode function may not have duplicate parameter names
5.不能访问arguments.caller和arguments.callee
(function() { "use strict"; var caller = arguments.caller; //Error var callee = arguments.callee; //Error })(); //TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
function() { "use strict"; var foo = {bar : "bar"}; with(foo) { console.log(bar); }; //SyntaxError: Strict mode code may not include a with statement }
### 4.参考文献 1. [Maintainable JavaScript](http://book.douban.com/subject/10547007/) 2. [ECMAScript 5 Strict Mode, JSON, and More](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)