嚴(yán)格模式開(kāi)啟檢測(cè)和一些其他措施,使JavaScript變成更整潔的語(yǔ)言。推薦使用嚴(yán)格模式。為了開(kāi)啟嚴(yán)格模式,只需在JavaScript文件或script標(biāo)簽第一行添加如下語(yǔ)句:
'use strict';
你也可以在每個(gè)函數(shù)上選擇性開(kāi)啟嚴(yán)格模式,只需將上面的代碼放在函數(shù)的開(kāi)頭:
function functionInStrictMode() {
'use strict';
}
下面的兩小節(jié)看下嚴(yán)格模式的三大好處。
讓我們看一個(gè)例子,嚴(yán)格模式給我們明確的錯(cuò)誤,否則JavaScript總是靜默失?。合旅娴暮瘮?shù) f() 執(zhí)行一些非法操作,它試圖更改所有字符串都有的只讀屬性——length:
function f() {
'abc'.length = 5;
}
當(dāng)你調(diào)用上面的函數(shù),它靜默失敗,賦值操作被簡(jiǎn)單忽略。讓我們將 f() 在嚴(yán)格模式下運(yùn)行:
function f_strict() {
'use strict';
'abc'.length = 5;
}
現(xiàn)在瀏覽器報(bào)給我們一些錯(cuò)誤:
> f_strict()
TypeError: Cannot assign to read only property 'length' of abc
在嚴(yán)格模式下,不作為方法的函數(shù)中的this值是undefined:
function f_strict() {
'use strict';
return this;
}
console.log(f_strict() === undefined); // true
在非嚴(yán)格模式下,this的值是被稱作全局對(duì)象(global object)(在瀏覽器里是window):
function f() {
return this;
}
console.log(f() === window); // true
不再自動(dòng)創(chuàng)建全局變量(No auto-created global variables) 在非嚴(yán)格模式下,如果你給不存在的變量賦值,JavaScript會(huì)自動(dòng)創(chuàng)建一個(gè)全局變量:
> function f() { foo = 5 }
> f() // 不會(huì)報(bào)錯(cuò)
> foo
5
在嚴(yán)格模式下,這會(huì)產(chǎn)生一個(gè)錯(cuò)誤:
> function f_strict() { 'use strict'; foo2 = 4; }
> f_strict()
ReferenceError: foo2 is not defined
更多建議: