ES5 引入了「嚴格模式」(Strict Mode)的概念。它的用意很直接:別讓 JavaScript 太宽容,把撰寫程式碼的規範要求拉高一點。
最典型的一點是,在嚴格模式下不能隱式宣告變數,必須帶 var。
在整份程式碼的開頭,或某個 function 的開頭,加上 "use strict" 即可。
放在檔案最前面,整份程式碼都必須遵循嚴格模式;放在 function 內部,則只有該函式受規範約束。
<!DOCTYPE html>
<head>
<title>strict mode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
// 啟用嚴格模式
"use strict";
function testFunction(){
var testvar = 4;
return testvar;
}
// 這裡會造成語法錯誤:testvar 從未宣告
testvar = 5;
</script>
</body>
</html>
因為全域啟用了嚴格模式,而函式外面的 testvar 沒有 var,不符合規範,執行時就會報錯。

<script>
function testFunction(){
"use strict";
testvar = 4;
return testvar;
}
testvar = 5;
</script>
打開 Chrome 開發者工具卻發現:竟然沒報錯。

原因很單純——我們根本沒呼叫 testFunction。沒有執行,自然不會啟用嚴格模式。補上呼叫再看:
<script>
function testFunction(){
"use strict";
testvar = 4;
return testvar;
}
// 呼叫 testFunction
testFunction();
testvar = 5;
</script>

這下就報錯了。可見嚴格模式確實夠嚴格,啟用之前得先想清楚。
變數:使用未以 var 宣告的變數。
testvar = 4;
delete:不能刪除變數、函式或 argument。
var testvar = 15;
function testFunc(){}
delete testvar; // 出錯
delete testFunc; // 出錯
屬性名:宣告物件時不能重複使用同一個屬性名。
var testObj = {
prop1: 10,
prop2: 15,
prop1: 20 // 出錯
}
參數名:函式參數不能重複。
function testFunc(param1, param1){ // 出錯
return 1;
}
保留字:以下這些未來可能成為關鍵字的識別符,不能用作變數名或函式名:
implements interface package private protected public static yield
八進位數值:不能將八進位字面量賦值給變數。
var testoctal = 010; // 出錯 var testescape = \010; // 出錯
this:當 this 為 null 或 undefined 時,不能被轉換成全域物件。
function testFunc(){ return this; }
var testvar = testFunc();
非嚴格模式下 testvar 會是全域物件,嚴格模式下則是 undefined。這其實是好事——避免函式誤寫到全域狀態上。
eval 與 arguments:不能作為函式名、參數名或變數名。
var eval = 10; // 出錯 var arguments = 10; // 出錯
arguments 的連動:不能透過修改 arguments 來改變對應的參數值。
function testArgs(oneArg){
arguments[0] = 20;
}
非嚴格模式下,改 arguments[0] 會連帶改變 oneArg;嚴格模式下兩者脫鉤,arguments 只是一份拷貝。
arguments.callee:不允許使用。
function(testInt){
if (testInt-- == 0) {
return;
}
arguments.callee(testInt); // 出錯
}
改用具名函式表達式遞迴即可避開這個限制,實際上也更清楚。