2016-03-05 80 views
1

知道之間的區別命名空間。JavaScript和/我需要whitout VAR

+4

[什麼是var關鍵字的功能以及何時使用它(或省略它)?](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var -key-and-when-use-it-or-omit-it) –

回答

2

就我個人而言,我從不忽略它。如果你離開var關鍵字,那麼如果變量在函數內聲明,那麼該變量將變成全局變量。這是因爲變量在JavaScript中具有函數級範圍。在給出的例子中,Namespace將是一個全局變量,無論您是否使用var或不是因爲它沒有在函數中聲明。您可以在下面的示例1中將var添加到Namespace變量中來測試該理論。

例1:

//I am a global variable with or without the var keyword because 
//I am declared outside of a function. 
Namespace = (function() { 
     return { 
      name: 'Module', 
      dep: ['d', 'a'] 
     }; 
})(); 


function test(){  

    Namespace = "I was changed because i have global scope"; 

} 

//Run the test function to gain access to the global variable inside. 
test(); 

//You will see that the value was changed by calling the test function 
console.log(Namespace); 

現在,如果你把你的Namespace變量的函數裏面,因爲它是現在它仍然是不var關鍵字的全局變量。在下面的示例中,我已將Namespace變量函數添加到var關鍵字中,使其成爲非全局函數。如果從示例2中的函數內的Namespace變量中刪除var關鍵字,則會看到它將成爲全局變量,腳本中的最後一個調用將從getNameSpace函數輸出Namespace值。

實施例2:

function getNameSpace(){ 

var Namespace = (function() { 
     return { 
      name: 'Module', 
      dep: ['d', 'a'] 
     }; 
})(); 


} 

function test(){  

Namespace = "I have global scope even inside a function because I am missing the var keyword."; 

} 

test(); 

//print the value of the global variable Namespace 
console.log(Namespace); 

//call get nameSpace 
getNameSpace(); 

//This will still print the value from the test function because the variable inside of 
//get Namespace has local or function level scope because it has the var keyword. 
console.log(Namespace); 

希望這一切現在更有意義。如果它不讓我知道,我會嘗試和幫助。要記住一件好事是始終使用var關鍵字,如果不希望腳本的另一部分直接訪問該變量,則將其放入函數(也稱爲閉包)中。

+0

令人敬畏的解釋拉里,謝謝! – Vercryger

+0

@JessicaManid沒有問題我知道還有其他答案,但如果你是初學者,他們並不總是容易跨過。 –

1

當您使用var時,您可以在函數的當前範圍內創建一個變量。 沒有var變量將在通常不好的全局範圍上創建。

使用var並且總是在一個封閉的範圍內(這不是全局範圍)創建你的變量,除非你有充分的理由不這樣做。

+0

對於非嚴格的環境來說,這是真實的。 –