Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

scope - Javascript function scoping and hoisting

I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}
b();
alert(a);

Using the code above, the browser will alert "1".

I'm still unsure why it returns "1". Some of the things he says come to mind like: All the function declarations are hoisted to the top. You can scope a variable using function. Still doesn't click for me.

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Function hoisting means that functions are moved to the top of their scope. That is,

function b() {  
   a = 10;  
   return;  
   function a() {} 
} 

will be rewritten by the interpeter to this

function b() {
  function a() {}
  a = 10;
  return;
}

Weird, eh?

Also, in this instance,

function a() {}

behaved the same as

var a = function () {};

So, in essence, this is what the code is doing:

var a = 1;                 //defines "a" in global scope
function b() {  
   var a = function () {}; //defines "a" in local scope 
   a = 10;                 //overwrites local variable "a"
   return;      
}       
b();       
alert(a);                 //alerts global variable "a"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...