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這種寫法意義不大。