// file.js "use strict" function doStuff(){ // use strict is enabled here! }這樣佻的file.js都會應用上"use strict"模式。
如果你僅想在一個函數中使用:
// file.js function a(){ "use strict"; // use strict is enabled in this context function nestedFunction(){ // and here too } }
好處
檢查對象中的重複鍵var zombie = { eyeLeft : 0, eyeRight: 1, // ... a lot of keys ... eyeLeft : 1 }
這段代碼會拋出一個錯誤因爲 eyeLeft 出現了兩次。這比你用眼睛去找錯誤要快多了。
未聲明變量
plane = 5;你現在已經知道忘記在這個變量前面加var了。不過如果你不知道,調試起來是非常痛苦的,因爲這個變量是聲明在全局上下文(global context)中的,而且可能被其他地方改掉。想象一下,如果你聲明瞭一個全局的 i, 在嵌套循環中可能會引起混亂。
重複的參數
function run(fromWhom, fromWhom){}注意fromWho出現了兩次,因此會拋出一個錯誤。
限制函數中的arguments
var run = function(fromWhom){ arguments[0] = 'alien'; alert(fromWhom); } run('zombie'); // alert: 'alien';現在你可以使用"use strict"
var run = function(fromWhom){ "use strict"; arguments[0] = 'alien'; alert(fromWhom); } run('zombie'); // alert: 'zombie';arguments[0] = 'alien' 改變了參數fromWhom,use strict 又節約了你的時間。