【问题标题】:Why this global variable is undefined inside a function? [duplicate]为什么这个全局变量在函数内部是未定义的? [复制]
【发布时间】:2017-11-24 16:42:16
【问题描述】:

如果同一个全局变量在同一个函数中重新声明和定义,为什么这个全局变量在函数中是未定义的?

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 //var a=2;
};
testscope();
console.log(a, 'outside func');

output:
1 "inside func"
1 "outside func" 

考虑相同的代码,其中 var a = 2;内部功能块未注释

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 var a=2; 
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"

【问题讨论】:

  • 欺骗目标太多...
  • 因为var ahoisted 到范围的顶部导致函数的开始是var a;
  • @T.J.Crowder 我正在撰写该评论 ;)
  • @j08691:22 个字符,两个错别字。这不是一个好的比例。 :-)(固定。)
  • @T.J.Crowder 感谢您的发现。我错过了之前提出的同一个问题。仍然投票支持这项努力。

标签: javascript


【解决方案1】:

这是因为 Javascript 不像 Java 和变量声明总是被推到他们的块。您的第二段代码严格等同于:

var a = 1;
function testscope(){
 var a;  // <-- When executed, the declaration goes up here
 console.log(a, 'inside func');
 a=2;  // <-- and assignation stays there
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"

【讨论】:

  • 拜托,明显的重复需要近距离投票和 cmets,而不是答案。
【解决方案2】:

因为第一个函数上的a指的是函数上存在的变量a,而a是在你写的变量之后写的。如果您希望在包含与全局变量相同的变量的函数内访问全局变量,则应添加 this.a。或者如果你想访问函数中的变量 a 你必须在调用它之前编写变量

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2021-06-20
    • 2012-12-17
    相关资源
    最近更新 更多