在 Javascript 中,如果我在函数之外的 javascript 中使用 var 声明变量
var foo = 1;
var bar = 2;
function someFunction() {
....
}
这些变量是否在文档或窗口的范围内?此外,为什么这很重要?我知道如果一个人声明一个没有 var 的变量,那么这个变量是全局的。
有没有一种简单的方法可以测试变量是否在文档或窗口的范围内?
在 Javascript 中,如果我在函数之外的 javascript 中使用 var 声明变量
var foo = 1;
var bar = 2;
function someFunction() {
....
}
这些变量是否在文档或窗口的范围内?此外,为什么这很重要?我知道如果一个人声明一个没有 var 的变量,那么这个变量是全局的。
有没有一种简单的方法可以测试变量是否在文档或窗口的范围内?
var
将变量的范围限制为定义它的函数,因此在顶层定义的变量 withvar
将有效地具有全局范围。
如果您将值分配给尚未限定范围的变量,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
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);
所以...
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
}
由于 JavaScript 只有函数作用域,因此var
关键字定义的变量的作用域是包含函数。
您可以通过在浏览器中打开 JavaScript 控制台(或直接在您的代码中)轻松检查全局范围,然后键入:
varRef && console.log(varRef)