關於Javascript中的"use strict"的那些事

"use strict"作用範圍

// 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 contextfunction nestedFunction(){ // and here too}

}

"use strict"的特性

檢查對象中的重複鍵

var zombie = { eyeLeft : 0, eyeRight: 1, // ... a lot of keys ... eyeLeft : 1}

這段代碼會拋出一個錯誤因為 eyeLeft 出現了兩次。這比你用眼睛去找錯誤要快多了。

重複的參數

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';

看懂了麼,就是這麼簡單


分享到:


相關文章: