[英]Variable shadowing and testing for existence before assignment in javascript
在下面的代碼片段中,我聲明了一個全局變量,然后檢查它在函數內的存在。
<script>
x = 5;
$(function() {
var x = x || 3;
console.log(x); // prints 3
});
</script>
這表現不同:
<script>
x = 5;
$(function() {
var y = x || 3;
console.log(y); // prints 5
});
</script>
我希望在第一個示例中,內部作用域中的變量聲明將檢測到x已經存在於全局作用域中,並獲取其值。 為什么第一個例子3?
具體來說,我最近編寫了一些檢查var _gaq = _gaq || []
代碼 var _gaq = _gaq || []
在一個jQuery就緒范圍內,當沒有任何東西被發布到Analytics時就感到困惑。
您正在尋找錯誤范圍內的x
。 由於變量提升, var x
實際上在x || 3
之前定義了一個值為undefined
的局部x
變量 x || 3
檢查發生:
var x = x || 3;
實際上是:
var x = undefined;
x = x || 3;
只需更改它以在window
對象上查找x
:
var x = window.x || 3;
第一個示例記錄3,因為any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope.
any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope.
因此,在第一種情況下,當分配本地x
時,由於它未初始化,因此它被分配3。
而在第二種情況下, x
指的是全局變量x
因為函數內部沒有x
聲明。
相反,如果你試試這個
<script>
x = 5;
$(function() {
x = x || 3;
console.log(x);
});
</script>
要么
<script>
x = 5;
$(function() {
var x = window.x || 3;
console.log(x);
});
</script>
你會得到預期的結果5
。
此外,與C及其系列(具有塊級范圍 )不同,JavaScript具有功能級范圍 。 塊(例如if語句)不會創建新范圍。 只有函數才能創建新范圍。
所以,如果我要寫類似的東西
#include <stdio.h>
int main() {
int x = 1;
printf("%d, ", x); // 1
if (1) {
int x = 2;
printf("%d, ", x); // 2
}
printf("%d\n", x); // 1
}
輸出: 1,2,1
相比於
var x = 1;
console.log(x); // 1
if (true) {
var x = 2;
console.log(x); // 2
}
console.log(x); // 2
輸出: 1,2,2
閱讀這篇關於JavaScript范圍和提升的優秀博客文章,以便更好地理解它。
函數中的var x
聲明x是函數的局部函數,因此在x || 3
x || 3
x不是全局x,因此未定義,因為它尚未初始化。
在var y = x || 3;
var y = x || 3;
x是全局x,因為沒有x本地函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.