Summary of domains and closures in js

Foreword: Scope is a very basic knowledge in js, and it is also a place that front-end interview questions like to examine.Understanding scope is also a prerequisite for using closures.

Scope understanding

1. First of all, understand that there is no block-level scope in js, only global scope and function scope in js;

  • Variables not declared in the body are global
  • Variables not declared with var are global

2. Then we need to understand that when scoping, it is the scope at which the definition is found, not the scope at runtime.

var a=200;
function fn(){
    var a=100;
    console.log('fn',a);
}
console.log('global',a);//200
fn();//100

3. The use of this, this, and scope are very different: this refers to the object at the time of call, not the object at the time of definition;

var wang={
  name : "Inside Object",
  fn : function fn(){
       console.log(this.name);
  }
};
wang.fn();//Inside Object
//Use call to change its domain so that this points to the object inside the call
wang.fn.call({name:"Change Scope"});

Functions like call also apply, bind
apply is similar to call, so here's how bind is used

var fn2=function(name){
   alert(name);
   console.log(this);
}.bind({y:200});  //bind(obj) This method converts this to point to obj i.e. this=obj
fn2('zhangsan');

4. Now that we know the above, we begin to talk about closures.
Closure: is the function inside a function that can be used externally to access the internal data of the function to prevent data contamination (Ruan Yifeng explained that a closure is a function that can read internal variables of other functions.)
eg: Write a function to determine if the data is the first occurrence

  function isFirstLoad() {
     var _list=[];//Defining arrays internally can effectively avoid data contamination
     return function(id){
        if(_list.indexOf(id) === -1){
           _list.push(id);
           console.log(_list);
           return true;
        }else{
           return false;
        }
     }
  }
  var FirstLoad=isFirstLoad();
  console.log(FirstLoad(10));//true
  console.log(FirstLoad(10));//false
  console.log(FirstLoad(20));//true
  console.log(FirstLoad(20));//fasle

Once you understand closures, let's move on to scenarios for using them

  • Return as a function
function F1(){
    var a=100;
    return function(){
        console.log(a);
    }
}
var f1=F1()
var a=200;
f1();//100
  • Passed as a function parameter
function F1(){
    var a=100;
    return function(){
        console.log(a);
    }
}
var f1=F1()
function F2(fn){
    var a=200;
    fn();
}
F2(f1)//100

Added by Vball on Sat, 11 Jul 2020 18:31:01 +0300