JS- context practice

/**
* JS because there is no block-level scope, if they are inside foo var form of a declaration, it will be lifted up,
* Is assigned the value undefined, undefined after representatives false, it will enter if statement block,
* Foo is assigned the value 10, so the following is printed out 10
*/
var foo =1;

function bar(){
    console.log(foo);  //  undefined
    if(!foo){
        var foo =10;
    }
    console.log(foo);   //  10
}
bar();
/**
* Calling b function, because of b function inside a function exists to enhance the function,
* Will be raised to the top, so the first printing is the function a () is assigned the next a 10,
* But this is only a function of a local variable inside the context, it will be destroyed after the run away,
* So when external print a still print out 1
*/
var a =1;
function b(){
    console.log(a);   // function a
    a =10;
    return;
    function a(){}
}
b();
console.log(a);     //  1
// function fn after execution, which generates the global context in a C, the following will generate a local environment B,
// After fn function call is completed, b will be destroyed, because the f is true, if it goes into generating a variable
var f =true;
if(f===true){
    var a =10;
}
function fn(){
    var b =20;
    c=30;

}
fn();
console.log(a); //  10
console.log(c); // 30
console.log(b); //  报错
/**
* Global there exist a first and b, values ​​are 3, after entering the IIFE, b is first executed = 5,
* This will find the global time, b, which was modified to 5, followed var a = b,
* This is a partial a, it's a global not be affected.
*/
 var a =b=3;
 (function(){
    var a =b=5;         //  b=5; var a =b;

 })()
 console.log(a);        //3
 console.log(b);  //  5
/**
* In the following foo function is lifted, the next code is printed first is the next function foo foo is assigned as A,
* Of the printed output A, after foo has been assigned a function, the print output function foo, calls foo, the output B, followed by the same
*/
console.log(foo);   //   function foo
var foo ='A';
console.log(foo);//  A
var foo =function(){
    console.log('B');
}
console.log(foo);  //  function foo
foo();
function foo(){
    console.log('C');
}
console.log(foo);
foo();//B
/**
B * is to be noted that the main function of which variable var a = 3 is present improved, so that b is a function inside the first undefined,
* Next in turn assigned a printout, but because it is a local variable, a global not affect
*/
 var a =1;
 function b(){
     console.log(a); // undefined
     a =2;
     console.log(a);//  2
     var a=3;
     console.log(a);//  3
 }
 console.log(a);//1
 b();
 console.log(a);// 1

 

Guess you like

Origin www.cnblogs.com/CccK-html/p/11488158.html