消除Javascript語法的一些不合理、不嚴謹之處,減小一些意外狀況出現;
消除代碼運行的一些不安全之處,保證代碼運行的安全;
提升編譯器效率,增長運行速度;
注意,一樣的代碼,在"嚴格模式"中,可能會有不同的運行結果;一些在"正常模式"下能夠運行的語句,在"嚴格模式"下將不能運行。html
"use strict"; x = 3.14; // 報錯 (x 未定義) "use strict"; x = {p1:10, p2:20}; // 報錯 (x 未定義)
"use strict"; var x = 3.14; delete x; // 報錯
"use strict"; function x(p1, p2) {}; delete x; // 報錯
"use strict"; function x(p1, p1) {}; // 報錯
"use strict"; var x = 010; // 報錯
"use strict"; var x = \010; // 報錯
"use strict"; var obj = {}; Object.defineProperty(obj, "x", {value:0, writable:false}); obj.x = 3.14; // 報錯
"use strict"; var obj = {get x() {return 0} }; obj.x = 3.14; // 報錯
"use strict"; delete Object.prototype; // 報錯
"use strict"; var eval = 3.14; // 報錯
"use strict"; var arguments = 3.14; // 報錯
"use strict"; with (Math){x = cos(2)}; // 報錯
"use strict"; eval ("var x = 2"); alert (x); // 報錯
function f(){ return !this; } // 返回false,由於"this"指向全局對象,"!this"就是false function f(){ "use strict"; return !this; } // 返回true,由於嚴格模式下,this的值爲undefined,因此"!this"爲true。 所以,使用構造函數時,若是忘了加new,this再也不指向全局對象,而是報錯。 function f(){ "use strict"; this.a = 1; }; f();// 報錯,this未定義
爲了向未來Javascript的新版本過渡,嚴格模式新增了一些保留關鍵字:安全
implements interface let package private protected public static yield "use strict"; var public = 1500; // 報錯
更多信息參考:菜鳥教程函數