void 0 與 undefined的區別

看到了這個麼一段代碼.chrome

function foo() {
                    var a  = arguments[0] !== (void 0 ) ? arguments[0] : 2;
                return a; 
        }

void 0 返回undefined,咱們都知道的,可是爲何不直接 arguments[0] !== undefined?工具

1.undefined能夠被重寫
undefined 在 ES5 中已是全局對象的一個只讀(read-only)屬性了,它不能被重寫。可是在局部做用域中,仍是能夠被重寫的。code

(function() {
var undefined = 10;對象

// 10 -- chrome
alert(undefined);
})();ip

(function() {
undefined = 10;作用域

// undefined -- chrome
alert(undefined);
})();io

2.爲何選擇void 0 做爲undefined的替代
void 運算符能對給定的表達式進行求值,而後返回 undefined。也就是說,void 後面你隨便跟上一個表達式,返回的都是 undefined,如 void (2), void (‘hello’)。而且void是不能被重寫的。但爲何是void 0 呢,void 0 是表達式中最短的。用 void 0 代替 undefined 能節省字節。很多 JavaScript 壓縮工具在壓縮過程當中,正是將 undefined 用 void 0 代替掉了。function

相關文章
相關標籤/搜索