Javascript - Precedence in hoisting

随声附和 提交于 2019-12-12 14:13:58

问题


In hoisting, do variables take precedence over function definition or the other way round? Please see the code below:

function a()
{
    var x = 10;

    function x() {
        return 20;
    }

    return x;
}

回答1:


It's not a matter of one taking precedence over the other (there is precedence taking place, but that's largely just a matter of semantics).

What matters here is that the assignment part of the variable declaration is not hoisted, whereas the entire function definition is.

Note Based on raina77ow's answer, it seems that part of my original assumptions were wrong. Functions are hoisted before variable declarations, but the net effect is the same.

After hoisting, your function will act like this:

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

the x = 10 takes place after all the hoisting is done, so that is the value that remains in x.


To respond to @thefourtheye's request (I think this is what s/he is asking for), if your original function looked like this:
function a() {
    function x() {
        return 20;
    }
    var x = 10;
    return x;
}

Then after hoisting, it would look like this (same as above):

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

As one last illustration, try this:

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

When called, this prints out:

function x() { return 20; }
10

The reason for this is that hoisting is causing the function to behave like this:

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



回答2:


You code would be equal to the following:

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

So when you call the function:

a() // 10


来源:https://stackoverflow.com/questions/27644694/javascript-precedence-in-hoisting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!