声明两个同名变量 [英] Declaring two variable with the same name
问题描述
是否可以调用在函数外设置的同名变量?
Is it possible to call the same name variables which set outside of the function?
var a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
var a = $(window).height(); // Not this one
alert(a);
}
推荐答案
在像您这样的代码片段中,变量 a
正在被重新定义.这是因为 if
语句不会为变量创建另一个作用域.但是,函数可以.
In a code snippet such as yours, the variable a
is being redefined. This is because an if
statement doesn't create another scope for variables. However, functions do.
在这种情况下:
var a = 0; // global
function doStuff() {
var a = 10; // local
alert(a);
alert(window.a)
}
alert(a);
doStuff();
alert(a);
在函数doStuff
中,变量a
被重新定义.因此,此剪辑将提醒数字 0
、10
、0
、0
.这证明全局变量没有在函数内部重新定义,因为在调用doStuff
后打印a
并不会改变a
的值全局范围.
inside the function doStuff
, the variable a
is being redefined. This snipped will therefore alert the numbers 0
, 10
, 0
, 0
. This proves that the global variable is not redefined inside the function, as printing a
after calling doStuff
doesn't change the value of a
in the global scope.
可以访问函数外部的变量 a
,因为任何未在非全局范围内声明的变量都放置在 window
对象内.但是,如果使用此代码段(调用匿名函数,创建新范围):
The variable a
outside of the function can be accessed, as any variable not declared in a non-global scope is placed inside the window
object. However, if using this snippet (which calls an anonymous function, creating a new scope):
var a = 0; // global
function doStuff() {
var a = 10; // local
alert(a);
alert(window.a)
function() {
var a = 20; // even more local
alert(a);
alert(window.a);
}();
}
alert(a);
doStuff();
alert(a);
您不能在 doStuff
函数中访问 a
的值.您仍然可以使用 window.a
访问全局变量.
you cannot access the value of a
inside the doStuff
function. You can still access the global variable using window.a
.
但是,在您的情况下,if
语句不会创建新范围,因此您将变量 a
重新定义为新值 $(window).height()
.
In your case, however, the if
statement does not create a new scope, therefore you are redefining the variable a
to the new value $(window).height()
.
这篇关于声明两个同名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!