Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - confused about function declaration in { }

var a;
if (true) {
  a = 5;

  function a() {}
  a = 0;
  console.log(a)
}
console.log(a)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following happens:

(1) There exist two variable declarations a, one inside the block and one outside of it.

(2) The function declaration gets hoisted, and bound to the inner blocks variable.

(3) a = 5 is reached, which overrides the block variable.

(4) the function declaration is reached, and the block variable is copied to the outer variable. Both are 5 now.

(5) a = 0 is reached, which overrides the block variable. The outer variable is not affected by this.

 var a1;
 if (true) {
   function a2() {} // hoisted
   a2 = 5;
   a1 = a2; // at the location of the declaration, the variable leaves the block      
   a2 = 0;
  console.log(a2)
}
console.log(a1);

This is actually not really part of the specification, it is part of the web legacy compatibility semantics, so don't declare functions inside blocks and don't rely on this code to behave in this way.

This is also explained here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...