SoFunction
Updated on 2025-04-07

Detailed explanation of several common forms of JS closures

Scope chain:

//Scope Chain  var a = 1;
  function test() {
    var b =2;
    return a;
  }
  alert(test());//Popt 1;  alert(b);//Cannot get b//scope chain
  var a = 1;
  function test() {
    var b = 2;
    function test1() {
      var c = 3;
      alert(a);
      alert(b);
      alert(c);
    }
    test1();
  }
  test();//pop up1,pop up2,pop up3;

Lexical scope:

//Lexical scope;  function f1() {
    var a = 12;
    return f2();
  }
  function f2() {
    return a;
  }
  alert(f1());//A cannot be obtained, a is not defined in f2();function f1() {
    var a = 1;
    return f2();
  }
  function f2() {
    var b = 3;
    alert(b);
    return a;
  }
  alert(f1());//Popt 3, a is not defined in f2()
function f1() {
    var a = 1;
    return f2();
  }
  function f2() {
    var b = 3;
    alert(b);
    return a;
  }
  alert(f1());//Popt 3, a is not defined in f2(), undefined  var a=55;
  alert(f1());//pop up3,pop up55

How to break through global scope chains through closures—several common forms

//Break through the global scope chain through closure  function f() {
    var a = "sun";
    return function () {
      return a;
    }
  }
  var test = f();
  alert(test());//Popt up sunvar n;
function f() {
  var a = "sun";
  n = function () {
    return a;
  }
}
f();
alert(n());//Popt up sun  function f(param) {
    var n =function () {
      return param;
    };
    param++;
    return n;
  }
  var test = f(45);
  alert(test());//pop up46;

Summarize

The above are several common forms of JS closures introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!