在javascript中赋值之前存在变量阴影和测试 [英] Variable shadowing and testing for existence before assignment in javascript

查看:67
本文介绍了在javascript中赋值之前存在变量阴影和测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the following code snippet I declare a global variable and then check for its presence inside a function.

<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?

I expect that in the first example, the variable declaration in the inner scope will detect that x already exists in the global scope, and take its value. Why does the first example 3?

具体来说,我最近编写了一些代码来检查 var _gaq = _gaq || [] 在一个jQuery就绪范围内,当没有任何东西被发布到分析时感到困惑。

Specifically I recently wrote some code that checks var _gaq = _gaq || [] in a jQuery ready scope and was confused when nothing was getting pubbed to Analytics.

推荐答案

你在错误的范围内寻找 x 。由于变量提升, var x 实际上定义了一个本地 x 变量,其值为 x ||之前未定义 3 检查发生:

You're looking for x in the wrong scope. Due to variable hoisting, var x has actually defined a local x variable with a value of undefined before your x || 3 check happens:

var x = x || 3;

实际上是:

var x = undefined;
x = x || 3;

只需更改它以查找 x on 窗口对象:

Simply change it to look for x on the window object:

var x = window.x || 3;

这篇关于在javascript中赋值之前存在变量阴影和测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆