On variable lift

Variable lift is a very common interview questions

For example, what is the difference between var and let?

One answer would not have let the variable lift

 

1. Concept

The most basic concept we all know

console.log(a);
var a = 1;

// 输出 undefined

 

In code using var to declare a variable, will mention the top of the current scope, and assignment unchanged in its place

The above two lines corresponding to

var a;
console.log(a);
a = 1;

 var a statement lifted up, a = 1 assignment left in place

 

2. The multiple script case

<Script> 
the console.log (A) 
</ Script> 
<Script> 
var. 1 = A; 
</ Script> 
// error console

 Such console on the error

ReferenceError: a is not defined

Variable can not cross-script to enhance the

 

3. Other cases

First, do not look directly assign var

console.log(a);  //ReferenceError: a is not defined
a = 1;

 The same error, because the use of variable var will upgrade (to my knowledge)

 

In standing if

  console.log(a) // undifined
  if(false){
    var a = 1;
  }

 Although if not passed, or to enhance the

 

4. lift function

Variable declaration will prompt, will function declaration

    console.log(foo);
    var foo=10;
    console.log(foo);
    function foo(){

    }
    console.log(foo);
  //输出 function a,10,10

 Function takes precedence over the first variable lift

The above code corresponds to

function a(){
}
var a;
console.log(a);
a=10;
console.log(a);

console.log(a);

 

At that time, if the function expression, it would only enhance this a variable, in line with previous variable logical upgrade

    a();
    var a = function () {
      console.log(1)
    }
//TypeError: a is not a function

 

Guess you like

Origin www.cnblogs.com/anxiaoyu/p/11490091.html