是否可以有两个具有相同名称的不同变量? [英] Is it possible to have two different variables with the same name?
问题描述
在jQuery中是否可以有两个具有相同名称的不同变量?
Is it possible to have two different variables in with the same name in jQuery?
我的jQuery链接到外部脚本.可以有两个使用相同字母名称的变量吗?
I have my jQuery linking to outside scripts. Is it possible to have two variables using the same letter name?
即:
包含在compressed.js中:
Contained in compressed.js:
var m = $$('li', s),
和
包含在 http://www.google.com/jsapi :
var m = "push",
这两个相互影响吗?
推荐答案
简单的答案是否",它们不会互相影响.
The simple answer is no, they will not effect each other.
它的工作方式是每个变量名都是唯一的,因此m
,m1
,m2
,m3
,m4
彼此之间没有任何影响:
how it works is that each variable name is unique, so m
,m1
,m2
,m3
,m4
does not have any affect to each other what so ever:
但是,根据设置为变量的值,您可以像这样访问和更改数据m[2]
的原因是m
是数组或某种对象,并且可以通过以下方式访问各个元素使用[]
可能会使您感到困惑.
However depending on the value set to the variable you may access and change data like so m[2]
the reason for this is that m
is an array or an object of some kind, and you can access the individual elements by using the []
which is probably where your getting confused.
变量如何相互影响的示例:
Example of how variables effect eachother:
var a = 'hello';
var b = 'world';
alert(a); //hello
alert(b); //world
alert(a + b); //helloworld
alert(b + a); //worldhello
a = b;
alert(a); //world
alert(b); //world
b = 'hey';
alert(b); //hey
从上面的示例中可以看到,
如果修改已经设置的变量的值,如果尚未设置该变量的赋值,它将更改该值;
as you can see from the examples above if you modify the value of a variable that has already been set it changes the value, if the variable has not already been set its assigned the value;
一个不错的技巧,您应该学习自调用匿名函数,我们使用它们的原因是创建一个将代码放入其中的框,这样它不会影响框外的任何其他事物.
a nice trick that you should learn self calling anonymous functions, the reason we use these is to create a box to put our code inside so it does not effect anything else outside the box.
示例
var hey = 'hey';
(function(){
var hey = 'bye'; //This is only effective inside the {}
alert(hey); //You get 'bye';
//Access the global scope
alert(window.hey); //You get 'hey';
//modifiy the external scope
window.hey = 'modified from within the function';
//expose vars inside the function scope to the global window:
window.exposed = hey; //Remember hey is internal and is set to 'bye';
})();
alert(exposed); //'bye';
alert(hey); //'modified from within the function'
希望您现在了解更多
这篇关于是否可以有两个具有相同名称的不同变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!