use strict 使用方法-簡單說
阿新 • • 發佈:2019-02-03
// 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';
var run = function(fromWhom){ "use strict"; arguments[0] = 'alien'; alert(fromWhom); } run('zombie'); // alert: 'zombie';arguments[0] = 'alien' 改變了引數fromWhom,use strict 又節約了你的時間。