由“var”全局定义的变量的范围是什么?
在Javascript中,如果我在函数外部使用JavaScript声明变量
var foo = 1;
var bar = 2;
function someFunction() {
....
}
是文档或窗口范围内的变量吗? 此外,为什么这很重要? 我知道如果一个变量没有var声明,那么这个变量是全局变量。
有没有简单的方法来测试一个变量是否属于文档或窗口的范围?
var foo = 1;
window.foo === foo;
JavaScript是一种功能性语言,因此在函数范围内声明的任何变量只能在该函数中使用。
JS实际上会遍历每个函数范围并寻找一个声明的变量。
function setGlobal() {
bar = 1; // gets set as window.bar because setGlobal does not define it
}
setGlobal();
// logs true and 1
console.log(window.bar === bar, bar);
http://jsfiddle.net/kXjrF/
所以...
function logGlobal() {
var bar;
console.log( foo, window.foo ) // undefined, undefined
function setGlobal() {
// window.foo is now set because logGlobal did not define foo
foo = 1;
bar = 2; // logGlobal's bar not window.bar
function makePrivate() {
var foo = 3; // local foo
console.log( foo ); // logs 3
}
makePrivate(); // logs 3
}
setGlobal();
console.log( foo, window.foo ); // logs 1, 1
}
var
将变量的范围限制为它所定义的函数,因此在顶层使用var
定义的变量将实际上具有全局范围。
如果你给一个没有用var
作用域的变量赋值,那么无论你在哪里定义它,它都会变成全局变量。
这里有一篇关于javascript范围的好文章:JavaScript中变量的范围是什么?
当你在JavaScript中声明一个函数时,它会创建一个范围。
当你声明一个变量,它必须有一个var
。 该var
决定了它属于哪个范围以及它在哪里可见。 如果它没有var
,那么它是一个变量的“赋值”,并且浏览器假定具有该名称的变量存在于外部作用域中。
当分配发生时,浏览器向外搜索,直到达到全局范围。 如果浏览器在全局范围内没有看到分配的变量,它将在全局范围内声明它(这不好)
例如,将以下内容作为范围可见性的演示,而不是实际的工作功能:
//global variables
var w = 20
var x = 10
function foo(){
function bar(){
//we assign x. since it's not declared with var
//the browser looks for x in the outer scopes
x = 0;
function baz(){
//we can still see and edit x here, turning it from 0 to 1
x = 1;
//redeclaring a variable makes it a local variable
//it does not affect the variable of the same name outside
//therefore within baz, w is 13 but outside, it's still 20
var w = 13;
//declaring y inside here, it does not exist in the outer scopes
//therefore y only exists in baz
var y = 2;
//failing to use var makes the browser look for the variable outside
//if there is none, the browser declares it as a global
z = 3;
}
}
}
//w = 20 - since the w inside was "redeclared" inside
//x = 1 - changed since all x operations were assigments
//y = undefined - never existed in the outside
//z = 3 - was turned into a global
链接地址: http://www.djcxy.com/p/59083.html
上一篇: What scope are variables globally defined by "var"?
下一篇: Iterating through an array while performing a request for each entry