0

I'm learning Javascript at the minute and have a question about hoisting/scoping - perhaps I'm missing something.

If I define a global variable, I cant reference that variable's value inside a function because its out of scope?

var x = "hello";
function temp(){
     console.log(x);
}

turns out to be

var x = "hello";
function temp(){
    var x;
    console.log(x);
}

which both outputs undefined. What are the points of global variables or how do you use them inside a function? - As I said what am i missing here! :)

Also hoisting works on functions? But NOT on anonymous functions? Correct?

Any help is appreciated!

Thanks!

4

2 回答 2

1

提升仅适用于局部变量(var在当前范围内声明的变量)。由于没有varin temp(),所以没有提升。

这里x将被吊起:

var x = "hello";
function temp(){
    console.log(x); // undefined
    var x = 55
}
temp()

因为这被解释为:

var x = "hello";
function temp(){
    var x /* = undefined */
    console.log(x);
    x = 55
}
temp()
于 2013-10-12T18:15:03.163 回答
0

您可以访问在您的范围或更高范围内定义的任何变量。如果在您的范围内重新声明了相同的变量名称,那么这将成为一个覆盖另一个变量的新变量定义。

所以,用这个例子:

var x = "hello";
function temp(){
     console.log(x);   // outputs "hello" when temp() is called
}

x定义在比函数更高的范围内,因此可以在函数内部使用。


在这个例子中:

var x = "hello";
function temp(){
    var x;
    console.log(x);   // outputs "undefined" when temp() is called
                      // because local var x has not been assigned a value
}

您已经定义了一个新变量x,它是函数内部的局部变量,它的值将一直存在undefined,直到您为其赋值。


术语“提升”意味着定义在范围内的任何地方(例如,在函数内)的变量的行为就像它是在函数的最开头定义的一样,无论声明实际出现在哪里。

所以,由于提升,这个例子:

var x = 10;
function temp() {
    x = 3;
    y = 4;
    var x;
    console.log(x);
}

行为是这样的,x函数内的所有引用都是对本地版本的x

var x = 10;
function temp() {
    var x;
    x = 3;
    y = 4;
    console.log(x);
}
于 2013-10-12T18:16:13.920 回答