JavaScript variable scope and closure operations

Variable scope:

Each function defines the scope, the function is declared with var, and their scope is only useful within this function. Functions can be used to create function scopes. At this time, the function is like a layer of translucent glass, you can see the variables outside the function inside the function, but you cannot see the variables inside the function outside the function.

function Foo ( ) {

    var i = 0 ;
    returnfunction(){
        console.log(i++);
    }
}
 
varf1=Foo(),
    f2=Foo();
f1 ( ) ;
f1 ( ) ;
f2();
The answer is: 0 1 0
 

function Foo ( ) {  

    var i = 0 ;   
    returnfunction(){  
        console.log(i++);
    }
}
 
var  f2 = Foo ( ) ;  
Foo()();
Foo()( );
f2();
The answer is: 0 0 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325306789&siteId=291194637