繁体   English   中英

Java语言吊装示例所需的说明

[英]Explanation Needed For A Javascript Hoisting Example

我正在研究一些Javascript提升概念,并遇到了这个示例。

console.log(a)
var a=5;

function a(){
console.log('In Console')
}

console.log(a)

输出是

function a() {
 console.log('In Console');
} 

5

我不了解两个console.logs的不同行为

谁能解释?

谢谢!

根据规格

  1. 让clarifiedFunctionNames为空列表。

  2. 令clarifiedVarNames为空列表。

15.bi令bindingExists为varEnvRec.HasBinding(vn)。

这意味着JS引擎将首先提升功能声明,并在遍历变量声明的同时检查该变量是否已具有该名称的绑定。

解释如下

// Before the following console statement function has been hoisted already and variable declaration is ignored.
console.log(a)

var a=5; // now the value of a is initialized.

//this statement has been hoisted above already
function a(){
console.log('In Console')
}

//value of a is 5 now
console.log(a)

随其主体悬挂的函数声明(按规范)。 因此,请在首次log之前将function a吊起。 然后,重新分配变量a ,第二个log 5。

因此,提升后,您的功能将变为以下内容:

var a;

a = function(){
    console.log('In Console')
}

console.log(a)
a=5;
console.log(a)
// at this point a is a function, variable below has not yet been assigned. 
// functions can be called from anywhere in the code file (not taking scope into account)
console.log(a)
// a is now assigned to a variable and assigned to 5, it no longer refers to the function
var a=5;

// function defined as a which can be called as a until a is reassigned
function a(){
console.log('In Console')
}

// a now refers to 5 at this point in the execution
console.log(a)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM