current position:Home>1. JavaScript variable promotion mechanism

1. JavaScript variable promotion mechanism

2021-08-27 12:03:18 HJ pocket sky

Can't write , If there is a mistake, please help correct it , thank you !

1. In order to make the code execute from top to bottom , First, it will open up a piece of memory ( Stack memory )=> Scope / Execution context context
2. Variable declarations ( promote )

When the browser opens up memory , And immediately execute the code from top to bottom , Instead, do the following operations first : Put all bands in the current scope var/function Keywords are declared and defined in advance => Variable promotion mechanism

 2.1  belt var We only declare in advance that (declare), No assignment , The default value is undefined.
 2.2  belt function Advance declaration , And define (defined),“a=13” Definition is assignment , To be precise , Is to associate a variable with a value .
 Copy code 
console.log(a); //undefined
var a=12;
var b=a;
b=13;
console.log(a); //12
console.log(b); //13
 Copy code 
console.log(sum(10.20)); //30
function sum(num1,num2){
    return num1+num2
}
 Copy code 

QQ Screenshot 20210823111603.png

3. The difference between function expression and function declaration :

QQ Screenshot 20210823111836.png

4. stay if In the judgment condition ( Global scope ):
4.1  Variable declaration is the same regardless of whether the condition is successful or not , Variable promotion is required ;
4.2  Under judgment conditions , Functions have special properties , Older browsers declare or define in advance ; In the new version , For compatibility es6 Grammatical norms of , You can only promote variables in advance , Cannot define in advance 
 Copy code 
console.log(fn); //undefined
// fn();  //=>fn is not function;
if('fn' in window){
    fn();  //=> Ha ha ha ;
    function fn(){
        console.log(" Ha ha ha ");
    }
};
fn(); // Ha ha ha 
 Copy code 
5. The self executing function itself does not carry out variable promotion ( No name )
 Self executing functions : Add in front () 、!、+、-、~, There is only one purpose , According to the grammar .


  
 Copy code 

copyright notice
author[HJ pocket sky],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827120315627q.html

Random recommended