The front end surface of the first to questions -js

JavaScript _01 interview questions (code below)

  var num = 10;

  fun();

  function fun(){

     console.log(num);

      var num = 20;

  }

Code output is: undefined ;

Resolution:

javascript is an interpreted scripting language, that is, to interpret a line one line (in fact, this statement is not correct, because before there is a pre-resolving process), js code is parsed by the browser parser, but there is a pre-parsing process, i.e. go first var, function, and parameters after the function and find var, var, and will function in advance, and then perform analytical line line, global scope analysis results as follows:

  var   num;
  function fun () { 
     console.log (whether); 
     var num = 20 ; 
  } 

  Whether = 10 ; 
  fun ();

       Resolution is performed, NUM = 10 ; and then calls the function Fun () ; parsed into the local scope, the following analysis results:

  var whether, 

  function fun () { 

     var   num; 

     console.log (whether); 

     Surely = 20 ; 

  } 

  Whether = 10 ; 

  fun ();

After the end of the pre-analytic, line by line to start the execution of the function inside, the statement num ; then console.log (num); this time num declared but not defined, so the output in the console undefined;

Javascript to add some points to note:

1. js has global scope and local scope, global scope: can be accessed at any location, local scope: variable declared inside a function, can only be used within the function.

2. global variables: the variables defined in the script or not part of a function; local variables: the variables inside a function defined;

3. No JavaScript block-level scope; in other languages, variables defined in the code block, the external access is not, but there is no block-level scope JavaScript, so the variables defined within the block are global, i.e., the outer block can be accessed;

4. Variable declarations are not used var global variables;

The internal function can access to a function outside the scope of the variables belongs (scope chain)

6. After exiting the variable scope will be destroyed, global variable close the page or browser will be destroyed;

Guess you like

Origin www.cnblogs.com/zangxin/p/10930299.html