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;
- 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;
- 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 var
variable 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, let
and const
have similar characteristics to prevent the variable lift, when the code is executed console.log(a)
, the execution of the change a
has never been defined, thus creating an error