The front part of the knowledge summary --2 js

1. JavaScript's "pre-interpretation" and "variable lift"

Look at the following code to output what?

var a= 1;
function f() {
  console.log(a);
  var a = 2;
}
f();

First answer is: undefined;

Process JavaScript running in the browser is divided into two stages of pre-interpretation phase, implementation phase;

  1. After reading var a, in the current scope to find out whether the same statement, if you do not create a variable named in the current scope of a collection, or ignore this statement be analytically;
  2. Next, V8 engine processes a = 2 assignment, the first will be asked whether the current scope has a variable named a, if there is an assignment, or continue to ask the parent scope

So the title: the scope of the function fn, first extract the variable declaration: var a; because the action has an assignment to a domain, so it will not continue to look for higher scope. Before the assignment and print, so it is undefined;

Look similar questions:

var a= 1;
function f() {
  console.log(a);
}
f(); // 1
var a= 1;
function f() {
  console.log(a);
  var a;
}
f(); //undefined

Function declarations and function expressions

We see that in the compiler processing stage, in addition to being varvariable declaration will enhance this characteristic variable outside the function will also have this feature, but the function function declarations and function expressions created two paradigms has shown different the result of.

F (); 
G (); 
// function declaration 
function F () { 
    the console.log ( 'F' ); 
} 
// function expression 
var G = function () { 
    the console.log ( 'G' ); 
};

//f

//报错:VM693:2 Uncaught TypeError: g is not a function

f () function declarations belong to enhance good understanding; but for the function expression g, was given undefined, undefeated and error can not be executed.

Conflict management

Conflict between variables

var a = 3;
var a = 4;
console.log(a); //4

Function conflict

f();
function f() {
    console.log('f');
}

function f () {
    console.log('g');
};
// g

3. The conflict between functions and variables

console.log(f);

function f() {
    console.log('f');
}
var f ='g';

ƒ f() {
console.log('f');
}

Description Function covering variables;

Similar let, there is a temporary dead zone:

 

function f() {
  console.log(a);
  let a = 2;
}
f(); 

 

报错: //ReferenceError: a is not defined

Undefined error code directly, letand consthave similar characteristics to prevent the variable lift, when the code is executed console.log(a), the execution of the change ahas never been defined, thus creating an error

Guess you like

Origin www.cnblogs.com/xiaozhumaopao/p/11622360.html