如何javascript初始化变量打印未定义?

时间:2011-03-01 10:58:47

标签: javascript

01  print(x === undefined); // prints "true"
02  var x = 3;
03   
04  //will return a value of undefined
05  var myvar = "my value";
06   
07  (function() {
08    alert(myvar);//undefined       -- here i don't understand ho it print undefined 
09    var myvar = "local value"
10  })();

2 个答案:

答案 0 :(得分:6)

因为hoisting。当函数执行时,var myvar = "local value"被推到函数的顶部,其值为undefined(覆盖先前定义的var myvar = "my value";)。

修改:在Adequately Good

中添加了稍加修改的示例

这意味着像这样的代码:

function foo() { 
    bar(); 
    var x = 1; 
}

实际上是这样解释的:

function foo() { 
    var x; 
    bar();
    alert(x); //alerts undefined 
    x = 1; 
}

答案 1 :(得分:1)

Javascript为变量创建一个名称,无论它在何处初始化。它实际上并没有在该代码行运行之后初始化变量。

print(x === undefined); // prints "true"
var x = 3;
print(x === undefined); // prints "false"