JavaScript variable hoisting explanation

隐身守侯 提交于 2021-02-16 08:59:11

问题


I came across the following article about variable hoisting in javascript. The article sums up the following three points.

1. All declarations, both functions and variables, are hoisted to the top of the containing scope, before any part of your code is executed.
2. Functions are hoisted first, and then variables.
3. Function declarations have priority over variable declarations, but not over variable assignments.

Site Point

var showState = function() {
  console.log("Idle");
};

function showState() {
  console.log("Ready");
} 

showState(); 

I understood that the code is interpreted by the javascript engine as

function showState() { // moved to the top (function declaration)
    console.log("Ready");
}

var showState; // moved to the top (variable declaration)
showState = function() { // left in place (variable assignment)
    console.log("Idle");
};

showState();

But, I couldn't get the meaning of the third point in the summary. Can anyone care to explain the third point? What is the meaning of the third point?

According to the explanation of the third point, the following snippet should return 8, function bar(). But it says undefined, function bar().

console.log(foo);
console.log(bar);
var foo = 8;
function bar() {
    console.log("bar");
}

回答1:


From the article you link to:

In the code above we saw that the function declaration takes precedence over the variable declaration. And in the next example we’ll see that when we have function declaration versus variable assignment, the last takes priority.

var showState = function() {
  console.log("Idle");
};

function showState() {
  console.log("Ready");
} 

showState();            // output: Idle

A function declaration does two things:

  1. It declares a variable with the same name as the function
  2. It assigns the function to that variable

Both of these are hoisted, not just the variable declaration. (This is unlike var statements with an associated assignment where only the declaration is hoisted).

This means that despite the = function() { code being first, the later function declaration still runs first so = function() { can overwrite it.




回答2:


Your last example is interpreted as

function bar() {
    console.log("bar");
}    
var foo;

console.log(foo); // here 'foo' is undefined
console.log(bar); // bar is of type function
foo = 8;



回答3:


Basically - lets say we have, in no particular order

function hello(){};
var sup;
var yo = 4;

with variable hoisting the order would become

    var yo = 4;
    function hello(){};
    var sup;

because the var assignment has priority over the function, which has priority over the function declaration.



来源:https://stackoverflow.com/questions/32645348/javascript-variable-hoisting-explanation

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