【发布时间】: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 a是hoisted 到范围的顶部导致函数的开始是var a;。 -
@T.J.Crowder 我正在撰写该评论 ;)
-
@j08691:22 个字符,两个错别字。这不是一个好的比例。 :-)(固定。)
-
@T.J.Crowder 感谢您的发现。我错过了之前提出的同一个问题。仍然投票支持这项努力。
标签: javascript