【问题标题】:Javascript - Precedence in hoistingJavascript - 提升优先级
【发布时间】:2014-12-25 06:14:53
【问题描述】:

在提升中,变量优先于函数定义还是相反?请看下面的代码:

function a()
{
    var x = 10;

    function x() {
        return 20;
    }

    return x;
}

【问题讨论】:

  • 我不会在有变量 x 和函数 x 的地方编写代码。 x 已被定义。它令人困惑的代码,不需要。在代码审查中,这是我会让程序员改变的事情。变量被提升到作用域的顶部,然后分配到它们被调用的地方。
  • ECMAScript 5.1 下,没有讨论提升。所以你不应该依赖任何特定的实现。最佳实践是在作用域顶部声明变量,然后在声明后初始化。

标签: javascript function hoisting


【解决方案1】:

这不是一个优先于另一个的问题(存在优先级,但这主要只是语义问题)。

这里重要的是变量声明的赋值部分没有提升,而整个函数定义

函数在变量声明之前被提升,但最终效果是一样的。

提升之后,你的函数会是这样的:

function a()
{
    var x = function x() {  // hoisted function declaration/definition
        return 20;
    };
    var x;                  // hoisted variable declaration
    x = 10;                 // unhoisted part of variable declaration
    return x;
}

x = 10 发生在所有提升完成后,所以这是 x 中保留的值。


要响应@thefourtheye 的请求(我认为这是她/他所要求的),如果您的原始功能如下所示:
function a() {
    function x() {
        return 20;
    }
    var x = 10;
    return x;
}

那么吊起来之后就是这个样子(同上):

function a() {
    var x = function x() {  // hoisted function declaration/definition
        return 20;
    }
    var x;                  // hoisted variable declaration (does nothing)
    x = 10;                 // unhoisted variable assignment
    return x;
}

作为最后一个例子,试试这个:

function a() {
    console.log(x);
    var x = 10;
    console.log(x);
    function x() { return 20; };
}

调用时,会打印出来:

function x() { return 20; }
10

原因是提升导致函数的行为如下:

function a() {
    var x = function x() { return 20; };
    var x;
    console.log(x);
    x = 10;
    console.log(x);
}

【讨论】:

  • 请交换varfunction并进行推理。
  • @thefourtheye 编辑了我的答案。那是你要求的吗?我不确定我是否理解您的要求。
  • It's not that the variable is taking precedence in hoisting - 所以,函数定义优先,对吧?
  • @JLRishe - 因此,函数定义将分解为函数运算符。但是故障是否像您所说的那样发生,还是会像 var x; x = 函数 x() .... ?
  • @thefourtheye 不,两者都不一定优先。关键是变量声明和函数定义的提升方式不同。对于变量声明,只有声明部分被提升,而对于函数定义,整个函数被提升。
【解决方案2】:

您的代码将等于以下内容:

function a() {
  var x;
  function x() { // this function is assigned to variable indicator "x"
    return 20;
  }
  x = 10; // this overrides the variable indicator "x"
  return x;
}

所以当你调用函数时:

a() // 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 2022-01-18
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多