嚴(yán)格模式(Strict mode)

2018-06-15 18:44 更新

嚴(yán)格模式開啟檢測(cè)和一些其他措施,使JavaScript變成更整潔的語(yǔ)言。推薦使用嚴(yán)格模式。為了開啟嚴(yán)格模式,只需在JavaScript文件或script標(biāo)簽第一行添加如下語(yǔ)句:

  1. 'use strict';

你也可以在每個(gè)函數(shù)上選擇性開啟嚴(yán)格模式,只需將上面的代碼放在函數(shù)的開頭:

  1. function functionInStrictMode() {
  2. 'use strict';
  3. }

下面的兩小節(jié)看下嚴(yán)格模式的三大好處。

明確錯(cuò)誤(Explicit errors)

讓我們看一個(gè)例子,嚴(yán)格模式給我們明確的錯(cuò)誤,否則JavaScript總是靜默失敗:下面的函數(shù) f() 執(zhí)行一些非法操作,它試圖更改所有字符串都有的只讀屬性——length:

  1. function f() {
  2. 'abc'.length = 5;
  3. }

當(dāng)你調(diào)用上面的函數(shù),它靜默失敗,賦值操作被簡(jiǎn)單忽略。讓我們將 f() 在嚴(yán)格模式下運(yùn)行:

  1. function f_strict() {
  2. 'use strict';
  3. 'abc'.length = 5;
  4. }

現(xiàn)在瀏覽器報(bào)給我們一些錯(cuò)誤:

  1. > f_strict()
  2. TypeError: Cannot assign to read only property 'length' of abc

不是方法的函數(shù)中的this(this in non-method functions)

在嚴(yán)格模式下,不作為方法的函數(shù)中的this值是undefined:

  1. function f_strict() {
  2. 'use strict';
  3. return this;
  4. }
  5. console.log(f_strict() === undefined); // true

在非嚴(yán)格模式下,this的值是被稱作全局對(duì)象(global object)(在瀏覽器里是window):

  1. function f() {
  2. return this;
  3. }
  4. console.log(f() === window); // true

不再自動(dòng)創(chuàng)建全局變量(No auto-created global variables) 在非嚴(yán)格模式下,如果你給不存在的變量賦值,JavaScript會(huì)自動(dòng)創(chuàng)建一個(gè)全局變量:

  1. > function f() { foo = 5 }
  2. > f() // 不會(huì)報(bào)錯(cuò)
  3. > foo
  4. 5

在嚴(yán)格模式下,這會(huì)產(chǎn)生一個(gè)錯(cuò)誤:

  1. > function f_strict() { 'use strict'; foo2 = 4; }
  2. > f_strict()
  3. ReferenceError: foo2 is not defined

深入閱讀

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)