2013-06-23 92 views
8

來自非javascript背景,我試圖圍繞'未定義'我的頭。 我寫了一個「isUndefined」功能如下:瞭解功能和undefined

function isUndefined(value) { 
    return (typeof value === 'undefined'); 
} 

,如果我在源類型本(其中變量「噓」不存在),我得到預期的結果「未定義的變量」。

if (typeof boo === 'undefined') { 
    console.log('undefined variable'); 
} 

,如果我在下面輸入: console.log (isUndefined(undefined));

我得到預期的結果 '真'

如果我輸入:console.log(isUndefined(boo));

我得到:

Reference Error: boo is not defined.

我希望得到'真實' - 所以我的問題是爲什麼第一個'直接'檢查undefined會返回預期的結果,但是函數()對它的測試不會呢?

+1

你是對被這個莫名其妙。 –

+0

你來自哪些背景? – galchen

+1

http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/ – goat

回答

7

有一個現有的變量,恰好包含了undefined價值,不存在在所有變量之間的差異。如果一個變量名不存在,那麼嘗試引用它是個錯誤。

typeof運算符是一種特殊情況:即使沒有該名稱的變量,它也會接受名稱。但只有當名稱實際使用typeof運營商。

在您的函數示例中,您使用一個不存在的名稱,並且在使用名稱處沒有typeof運算符。這就是發生錯誤的地方。無需將名稱傳遞給將使用typeof的函數;該函數永遠不會被調用,因爲錯誤已經發生。

如果您給它一個現有的變量名稱,您的函數將按預期工作。然後,它會告訴你,如果該變量的值undefined與否:

var boo; // now boo exists but has the undefined value 
console.log(isUndefined(boo)); // will log 'true' 

如果你檢查一個全局變量,它會如果你說window.boo,而不是僅僅boo工作。這是因爲引用對象的不存在的屬性並不是錯誤;它只是給你的undefined值,當你這樣做:

// logs 'true' if there is no global 'boo' 
console.log(isUndefined(window.boo)); 

,如果你想檢查本地變量是否存在,但是,因爲它不會是window的屬性,是行不通的目的。

3

讓我把這樣的:

var a = 5; 
function foo(v){ 
    v += 5; 
    console.log(v); 
} 

foo(a); 
console.log(a); // will give you 5, not 10 

出於同樣的原因 - 當你調用

isUndefined(boo) 

變量boo不發送,噓的值發送。由於在調用過程中沒有定義boo,因此在嘗試達到其值時會出現錯誤。

值得一提的是typeof不是一個函數,這是一個運營商

2

通常,Javascript中試圖訪問不存在變量的行爲是拋出ReferenceError。 typeof運算符在這裏是個例外,因爲如果你把它傳遞給一個不存在的變量,它的特殊編碼就不會給出這樣的錯誤。

http://es5.github.io/#x11.4.3

11.4.3 The typeof Operator # Ⓣ

The production UnaryExpression : typeof UnaryExpression is evaluated as follows:

Let val be the result of evaluating UnaryExpression. 

If Type(val) is Reference, then 

    If IsUnresolvableReference(val) is true, return "undefined". 

    Let val be GetValue(val). 

爲了避免引發ReferenceError你可以聲明boo事先沒有給它分配任何東西:

var boo; 
console.log(isUndefined(boo)); 
console.log(typeof boo == 'undefined')