【问题标题】:Javascript Hoisting/ScopeJavascript 提升/作用域
【发布时间】:2013-10-20 16:18:38
【问题描述】:

我现在正在学习 Javascript,并且有一个关于提升/作用域的问题 - 也许我遗漏了一些东西。

如果我定义了一个全局变量,我不能在函数中引用该变量的值,因为它超出了范围?

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

原来是

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

这两个输出未定义。全局变量的要点是什么,或者如何在函数中使用它们? - 正如我所说,我在这里错过了什么! :)

提升也适用于功能?但不在匿名函数上?正确的?

感谢任何帮助!

谢谢!

【问题讨论】:

标签: javascript scope scoping hoisting


【解决方案1】:

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

所以,用这个例子:

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);
}

【讨论】:

    【解决方案2】:

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

    这里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()
    

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2020-07-01
      • 2023-03-28
      • 1970-01-01
      • 2015-06-22
      相关资源
      最近更新 更多