javascript中"return obj === void 0"這種寫法的原因和好處

來源:互聯網
上載者:User

javascript中"return obj === void 0"這種寫法的原因和好處

學習underscore.js的時候,發現源碼中經常出現類似下面的代碼:

if (context === void 0) return func;if (array == null) return void 0;

 

以前沒有見過這種寫法,到網上搜了一些資料,剛好發現stackoverflow上也有人提出類似的疑問。這裡總結歸納下,做個筆記。void其實是javascript中的一個函數,接受一個參數,傳回值永遠是undefined。可以說,使用void目的就是為了得到javascript中的undefined。Sovoid 0 is a correct and standard way to produce undefined.

void 0void (0)void hellovoid (new Date())//all will return undefined

 

為什麼不直接使用undefined呢?主要有2個原因:

1、使用void 0比使用undefined能夠減少3個位元組。雖然這是個優勢,個人但感覺意義不大,犧牲了可讀性和簡單性。

>undefined.length9>void 0.length6

 

2、undefined並不是javascript中的保留字,我們可以使用undefined作為變數名字,然後給它賦值。

alert(undefined); //alerts undefinedvar undefined = new value;alert(undefined) //alerts new value

Because of this, you cannot safely rely on undefined having the value that you expect。

void, on the other hand, cannot be overidden. void 0 will always return。

我在IE10,Firefox和chrome下測試,遺憾的是沒有出現預期的結果。雖然上面的代碼沒有報錯,但是並沒有列印出我們期望的new value。

 

所以總體來說,使用void 0這種寫法意義不大。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.