Functions Scope in JavaScript

2019-08-02 07:29发布

问题:

In Pro JavaScript with Mootools book I have found the below line

The scoping rules for function expressions are a bit different from function 
declarations because they depend on variable scoping. Remember that in 
JavaScript, the var keyword defines a variable to be scoped locally, and 
omitting the keyword creates a global variable instead:    

As per my understanding I have written the below code and tried to check this

var a = function(){ 
   b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'

And I also tried below

var a = function(){ 
   var b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'​​

Could you please explain this to make me understand better. As per my understanding in first block of code b and c should be global variables.. But this is not happening in this case. Even I tried to invoke a() before alerts... Here is the fiddle. Please help me on this to understand scope better.

回答1:

As per my understanding in first block of code b and c should be global variables

They are, but they won't have values assigned to them until a is called (and until b is called in the case of c).

Here is the fiddle

That code is different. You have var b, which makes b a local variable and not a global.


var a = function(){ 
   b = function(){ c = function(){ alert("b"); }; };
};
a();
b();
alert(typeof a); 
alert(typeof b); 
alert(typeof c); 


回答2:

Google the key word below, it is a good place to master scoping and other javascript pattern techniques. It is a series of articles with 12 parts. There are no direct links on the website so you need search for the rest of the articles using part number

  search for
   
    elegant code basic javascript part 1
    elegant code basic javascript part 2
    etc...