如果变量在JS中的大括号之外,如何使用变量?

时间:2013-02-28 19:14:49

标签: javascript

我不理解这一点 - 在var条件中定义的if如何在该条件之外使用?

示例JS:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

呈现:myVar = I live in brackets

myVar条件内的if (1===2)范围不是吗?

4 个答案:

答案 0 :(得分:2)

范围仅适用于函数,而不适用于其他块。

答案 1 :(得分:2)

Javascript 阻止范围,它只有功能范围

换句话说,var声明的变量可以在函数的范围内访问,无处不在,只在那里,而不是在外面。

答案 2 :(得分:1)

由于hoisting,每个变量声明都会弹出函数范围的顶部。

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error

答案 3 :(得分:0)

当定义了一个javascript变量时,声明将被提升到函数范围的顶部。

所以这个:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

等同于此

var myVar;
if (1===2) {
  myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

因此,函数中定义的任何变量都可以在该函数的任何位置访问,也可以在任何内部函数内访问。在功能之外无法访问它们。

所以

(function(){
    if (1===2) {
      var myVar = "I live in brackets";
}}())
$("#debug").append("myVar = " + myVar); //reference exception
相关问题