Javascript / jQuery有系统变量吗? [英] Does Javascript / jQuery have system vars?
问题描述
我注意到了一个奇怪的问题。
I noticed strange issue.
看看这个jQuery:
Look at this jQuery:
$(function(){
status = 1;
status1 = 2;
$('body').append(status+' - '+status1);
});
如您所见,输出为:
- 2
所以状态
是JavaScript或jQuery的系统变量吗?
So status
is system var for JavaScript or jQuery?
还有这样的其他变种吗?
And is there any other vars like this?
推荐答案
JavaScript有全局变量,在浏览器中,全局变量是 全局对象 窗口
。
JavaScript has global variables and in browsers, global variables are properties of the global object which is window
.
现在,窗口
本身有几个预定义的属性,其中一些是只读的,如 window.status
[MDN] (这也可能因浏览器而异!)。因此,使用这样的名称创建全局变量将失败(变量已存在,但您无法为其分配新值)。
Now, window
itself has a couple of predefined properties and some of them are read-only, like window.status
[MDN] (this can also differ from browser to browser!). Creating a global variable with such a name will therefore fail (the variable already exists, but you cannot assign a new value to it).
您可以找到预定义的列表 MDN文档中的属性。
You can find a list of predefined properties in the MDN documentation.
这是避免全局变量的原因之一。如果使用局部变量(通过使用 var
声明变量,并且如果需要,将所有代码放在函数中),则不会出现此问题:
This one of the reasons why you should avoid global variables. If you use local variables (by declaring variables with var
and if necessary, put all your code in a function), you don't have this problem:
(function() {
var status = 'foo';
// ....
}());
这篇关于Javascript / jQuery有系统变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!