[英]Accessing global variable defined inside a function
我試圖理解 Javascript 中的變量范圍,一個朋友問了我這個問題。 我可以在這里使用一些幫助。
function abc(){
var a = b = 10; // a is local, b is global variable. Right?
c = 5; // c is global variable
}
d = 20; // d is global variable
console.log(b); // b is not defined error. Why? Isn't b a global variable?
console.log(c); // Again, Why is 'c not defined'.
我在 chrome 控制台中運行了這段代碼。 我不應該在控制台中期待 10 和 5 嗎? 它給出了“b 未定義”,“c 未定義”錯誤。 如果 b, c 是全局變量,為什么會發生這種情況? console.log(d) 工作得很好。
這是一個小提琴。
如果
b
,c
是全局變量,為什么會發生這種情況?
b
和c
僅在您實際調用abc
創建。 僅僅定義函數並不能神奇地執行它的主體。
function abc(){
var a = b = 10; // a is local, b is global variable.
c = 5; // c is global variable
}
// call abc to execute the statements inside the function
abc();
console.log(b); // 10
console.log(c); // 5
也就是說,隱式創建全局變量仍然不好。 如果可能,請避免使用全局變量,如果沒有,請通過分配給全局對象(瀏覽器中的window
)來顯式聲明它們。
編輯:這就是我喜歡 SO 的原因,即使您無所不知,您也能學到一些知識,並回答您顯然無法回答的問題。 感謝@FelixKling 的澄清,我已經更新了這個以反映
var
s
所以這里有一些術語混淆:
Javascript 具有函數級作用域:由於a
和b
在function
塊內聲明,它們對於它們在其中聲明的function
是本地的,並且被限制在function
的作用域內。
在函數外部(或在window
對象的瀏覽器中,在global
對象的 node 中)定義的變量具有global
作用域。
所以var
關鍵字實際上與global
作用域沒有任何關系,作用域由您聲明變量的位置定義。
以你的例子為例:
function abc(){
var a = b = 10; //a is local, b is global (see @FelixKling's answer)
c = 5; // c is global as it is not prefixed with the `var` keyword
}
var d = 20; // d is global
console.log(a); // logs "10" to the console
console.log(b); // b is not defined
console.log(c); // 'c not defined'.
console.log(d); // logs 20 to the console.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.