Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中赋值前的变量隐藏和存在性测试_Javascript_Shadowing - Fatal编程技术网

javascript中赋值前的变量隐藏和存在性测试

javascript中赋值前的变量隐藏和存在性测试,javascript,shadowing,Javascript,Shadowing,在下面的代码片段中,我声明了一个全局变量,然后检查它是否存在于函数中 <script> x = 5; $(function() { var x = x || 3; console.log(x); // prints 3 }); </script> x=5; $(函数(){ var x=x | | 3; console.log(x);//打印3 }); 其表现不同: <script> x = 5; $(function() { var y

在下面的代码片段中,我声明了一个全局变量,然后检查它是否存在于函数中

<script>
x = 5;
$(function() {
   var x = x || 3;
   console.log(x); // prints 3
});
</script>

x=5;
$(函数(){
var x=x | | 3;
console.log(x);//打印3
});
其表现不同:

<script>
x = 5;
$(function() {
   var y = x || 3;
   console.log(y); // prints 5
});
</script>

x=5;
$(函数(){
变量y=x | | 3;
console.log(y);//打印5
});
我希望在第一个示例中,内部作用域中的变量声明将检测到全局作用域中已经存在x,并获取其值。为什么第一个例子是3


具体地说,我最近编写了一些代码,检查jQuery就绪范围中的
var\u gaq=\u gaq | |【】
,当没有任何东西被发布到分析时,我感到困惑。

函数中的
var x
声明x是函数的局部,因此,在
x | | 3
x中,不是全局x,因此未定义,因为它尚未初始化


vary=x | | 3
x是全局x,因为函数中没有x本地。

您在错误的范围中查找
x
。由于变量提升,
var x
在执行
x | | 3
检查之前,实际上定义了一个值为
未定义的本地
x
变量:

<script>
x = 5;
$(function() {
   var x = x || 3;
   console.log(x); // prints 3
});
</script>
var x = x || 3;
实际上是:

var x = undefined;
x = x || 3;
只需将其更改为在
窗口
对象上查找
x

var x = window.x || 3;

第一个示例记录3,因为
在函数中使用var关键字初始化的任何变量都将具有局部作用域。如果在没有var的函数中初始化变量,则该变量将具有全局作用域。

因此,在第一种情况下,当本地
x
被分配时,因为它未初始化,所以被分配为3

而在第二种情况下,
x
指的是全局变量
x
,因为函数中没有
x
的声明

<script>
x = 5;
$(function() {
   var x = x || 3;
   console.log(x); // prints 3
});
</script>
相反,如果你试试这个

<script>
x = 5;
$(function() {
   x = x || 3;
   console.log(x);
});
</script>
输出: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


浏览上这篇优秀的博文,以便更好地理解它。

我还应该提到,正是出于这个原因,我将变量初始化与赋值分离开来。我知道写
var-foo有点冗长;foo=bar,但它使这个特定问题更加突出。