当前位置:网站首页>JS precompile - Variable - scope - closure

JS precompile - Variable - scope - closure

2022-06-26 07:58:00 Small slag bright

js Stack and heap of

  • Stack : Stored are values of simple data types , And the address of complex data ( That is, the execution environment )
  • Pile up : Stored are values of complex data types , This is stored in the stack first ( Keep an address ), This address points to the values in the heap !

Storage of complex objects

 Insert picture description here

js Precompilation

  • precompile : Is in the js Before it is actually parsed ,js The parsing engine will first preprocess the entire file ;
    • var Declared variables have variable promotion !

The first question is

	  console.log(a)
      var a = 10
      console.log(a)
      function a() {
    
        console.log(a)
      }
      a()
      //  analysis :
      // js Pre analysis of , Yes var Declared variable promotion , There is no assignment to it , Implement function promotion for functions first , But no function is called 
      // var a; underfined
      // a = f a() { console.log(a) }
      // console.log(a) -> f a() { console.log(a) }
      // a = 10;
      // console.log(a) -> 10
      // a(); -> a be equal to 10 了   Instead of functions !

      //  result :
      // ƒ a() {
    
      // console.log(a);
      // }
      // a is not a function

The second question is

eg1:
      a()
      var a = 10
      function a() {
    
        console.log(1)
      }
      a()
      // var a;
      // a = f a () { console.log(1) }
      // a()
      // a = 10
      // a();
      //  result : 1 a is not a function

eg2:
	  console.log(num)
      var num = 10 //  result  undefined

 Insert picture description here

Variable

  • Global variables : Life cycle ( permanent ) Accessibility ( Can be accessed anywhere )
  • local variable : Life cycle ( Delete immediately after function execution ) Accessibility ( Can only be accessed inside a function )
  • Free variable : Life cycle ( permanent ) Accessibility ( Access... Only inside functions );
    • In the case of closures, a special variable is generated

Global variables

  • Global variable declaration method
    • var Variables defined
    • Not used var Variables defined ( Not used let、const)
    • window.XXX Statement
<template>
  <div>Home</div>
</template>

<script>
export default {
    
  name: 'Home',
  components: {
    },
  data() {
    
    return {
    
      msg: '1111'
    }
  },
  created() {
    
    this.init()
  },
  methods: {
    
    init() {
    
      var num = 10 //  Global variables 
      // test = 'test'
      window.b = 'bbb'
      console.log('init', num)
      function bbb() {
    
        console.log('bbb function ', num, 'b', b)
      }
      bbb()
      //  result  init 10 ; bbb function  10 b bbb
    }
  }
}
</script>

local variable

  • Is the variable declared in the function body
    • When a function is called, an execution environment will be generated , This variable is declared as a local scope in the current environment , Can only be accessed within this scope , At the end of function execution , The variable is destroyed !
      var a = 10 //  Global variables 
      function test() {
    
        var b = 20 //  local variable 
        console.log('b', b, 'a', a)
      }
      test()
      console.log('b', b)
      //  result :b 20 a 10 ; b is not defined( because b Variables declared in a function are local variables , I can't get outside )

Free variable

  • effect :
    • 01: Called at any time , Will not be destroyed !
    • 02: Ensure data privacy => Only your function can use ;
      let a = 10 //  Global variables 
      function test() {
    
        let b = 20
        console.log(' Free variable ', b + a) //  Free variable  30
      }
      test()
      //  Free variable : It refers to the external variables inside the function ,

Scope

Global scope

  • That is, the declared variables are attached to window On the object , The global scope is window object

Local scope

  • After the function call , An execution environment , A local scope is the currently generated execution environment

Scope chain

  • Comprehensiveness : If your internal function doesn't define variables , Then it will go out to the outer layer to find this variable , Until you find window here , If it were not so , It outputs undefined
  • General : Finding variable paths is a scope chain , Find variables according to the principle of proximity , First, I will search from my own area , If you have, you can directly use your own variables , It does not look up one level , Stop searching until you find the position of the variable , If there is no overall situation , Find this variable , That would be a mistake , This variable is not defined

Closure

  • If the variables of the external function are used in the internal function , It's a closure , Closures retain references to external environments
  • If the inner function is returned outside the outer function , After the execution of the external function , You can still use the values in the closure
  • Closure formation : Use variables of external functions in internal functions , It's a closure , Closure is an extension of the current scope !

Closure formation

eg1:
	// test External function  bbb Internal function 
      function test() {
    
        var a = 100
        // bbb The function uses  a Variable  ->  It forms a closure 
        function bbb() {
    
          console.log('bbb function ', a)
        }
        bbb()
      }
      test()

eg2:
      function test() {
    
        // bbb The function uses  a Variable  ->  It forms a closure 
        function bbb() {
    
          console.log('bbb function ', bbb)
        }
        bbb()
      }
      test()
  //  analysis :
  // test call :
  // test Execution environment ( Pre parse ) bbb = function
  // bbb call   Output bbb For a function 

Maintenance of closures

  • The above closures produce , After the function call is executed , The variables inside will still be destroyed , To maintain the persistence of the current variable , You need to return a function on the inner function ( This function uses the variables of an external function )
      function test() {
    
        // bbb The function uses  a Variable  ->  It forms a closure 
        var num = 0
        function bbb() {
    
          console.log('bbb function ', num++) //  To form a closure 
        }
        return bbb
      }
      var demo = test()
      console.log('demo', demo)
      demo()
      demo()
      //  analysis 
      // test Call to :
      // test execution environment  { num:underfined, bbb:fun }
      //  At present test function   The return is  bbb function 
      //  Then on test assignment   A function bbb function  log Output  f bbb(){}
      //  call demo  Equivalent to  bbb() -> log Priority output  num The value is 0  And then add 
      //  Then call demo() -> log Priority output num The value is 1  And then add 

      //  result 
      // demo ƒ bbb()
      // 0 1

The function of closures

demand : Click on ul Medium li, Output the corresponding index number

// demand : Using closures , To click on the current small li Get the current small li The index number of 
    var lis = document.querySelectorAll("li");
    for (var i = 0; i < lis.length; i++) {
    
      // Using closures , Put the current i As a parameter, it is passed into the immediate execution function , Before starting the current click event , Print the corresponding index number !
      (function (num) {
    
        lis[i].onclick = function () {
    
          console.log(num);
        }
      })(i)
    }

The throttle function of closure

// demand : Using closures , Encapsulate a function for throttling and anti chattering  
    //throttle ---  throttle  antiShake --- Shake proof 
    // Throttling package  
    //  Parameters 1: Callback function ( What is written in it is the function of consumption performance )  Parameters 2: Delay time   Parameters 3: change this The direction of !
    function throttle(callback, delay, context) {
    
      var flag = true;
      delay = delay || 100;
      return function () {
     // Generating closures 
        if (flag) {
    
          flag = false;
          setTimeout(function () {
    
            context ? callback.call(context) : callback();
            flag = true;
          }, 200)
        }
      }
    }
    // document.onscroll = throttle(function () {
    
    // console.log(" Functions that consume performance ");
    // }, 200)

Anti shake function of closure

// Debounce the package 
    // Parameters 1: Callback function   Parameters 2: Delay time   Parameters 3: change this The direction of 
    function antiShake(callback, delay, context) {
    
      var timer = "";
      var delay = delay || 100;
      return function () {
     // Generating closures 
        clearInterval(timer)
        timer = setTimeout(function () {
    
          context ? callback.call(context) : callback();
        }, 200)
      }
    }
    // document.onscroll = antiShake(function () {
    
    // console.log(" Consuming performance 2");
    // }, 200)
原网站

版权声明
本文为[Small slag bright]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170607284280.html