繁体   English   中英

访问函数内定义的全局变量

[英]Accessing global variable defined inside a function

我试图理解 Javascript 中的变量范围,一个朋友问了我这个问题。 我可以在这里使用一些帮助。

function abc(){
  var a = b = 10; // a is local, b is global variable. Right?
  c = 5; // c is global variable
}
d = 20; // d is global variable

console.log(b); // b is not defined error. Why? Isn't b a global variable?
console.log(c); // Again, Why is 'c not defined'.

我在 chrome 控制台中运行了这段代码。 我不应该在控制台中期待 10 和 5 吗? 它给出了“b 未定义”,“c 未定义”错误。 如果 b, c 是全局变量,为什么会发生这种情况? console.log(d) 工作得很好。

这是一个小提琴

如果b , c是全局变量,为什么会发生这种情况?

bc仅在您实际调用abc创建。 仅仅定义函数并不能神奇地执行它的主体。

function abc(){
  var a = b = 10; // a is local, b is global variable.
  c = 5; // c is global variable
}

// call abc to execute the statements inside the function
abc();

console.log(b); // 10
console.log(c); // 5

也就是说,隐式创建全局变量仍然不好。 如果可能,请避免使用全局变量,如果没有,请通过分配给全局对象(浏览器中的window )来显式声明它们。

编辑:这就是我喜欢 SO 的原因,即使您无所不知,您也能学到一些知识,并回答您显然无法回答的问题。 感谢@FelixKling 的澄清,我已经更新了这个以反映var s

所以这里有一些术语混淆:

Javascript 具有函数级作用域:由于abfunction块内声明,它们对于它们在其中声明的function是本地的,并且被限制在function的作用域内。

函数外部(或在window对象的浏览器中,在global对象的 node 中)定义的变量具有global作用域。

所以var关键字实际上与global作用域没有任何关系,作用域由您声明变量的位置定义。

以你的例子为例:

function abc(){
  var a = b = 10; //a is local, b is global (see @FelixKling's answer)
  c = 5; // c is global as it is not prefixed with the `var` keyword 
}
var d = 20; // d is global 


console.log(a); // logs "10" to the console
console.log(b); // b is not defined
console.log(c); // 'c not defined'.
console.log(d); // logs 20 to the console. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM