JavaScript变量吊装说明 [英] JavaScript variable hoisting explanation

查看:61
本文介绍了JavaScript变量吊装说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下有关javascript中的变量提升的文章.本文总结了以下三点.

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.

站点点

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

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

showState(); 

我了解到,JavaScript引擎将代码解释为

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?

根据第三点的说明,以下代码段应返回8,功能为bar().但是它说未定义的功能bar().

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

推荐答案

从您链接到的文章中:

在上面的代码中,我们看到了函数声明优先于变量声明.在下一个示例中我们会看到,当我们有函数声明与变量分配,最后一个优先.

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

函数声明有两件事:

  1. 它声明与该函数同名的变量
  2. 它将功能分配给该变量

这两个都是悬挂的,而不仅仅是变量声明.(这与带有关联分配的 var 语句不同,在该语句中,仅声明被悬挂).

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).

这意味着,尽管首先使用 = function(){代码,但是以后函数声明仍将首先运行,因此 = function(){可以覆盖它.

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

这篇关于JavaScript变量吊装说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆