Home > Web Front-end > JS Tutorial > Detailed explanation of common forms of JS closures

Detailed explanation of common forms of JS closures

巴扎黑
Release: 2017-09-18 09:28:12
Original
2042 people have browsed it

This article introduces several common forms of js closures in detail through example codes. The code is simple and easy to understand, very good, and has reference value. Friends who need it can refer to

Scope Chain:


//作用域链
  var a = 1;
  function test() {
    var b =2;
    return a;
  }
  alert(test());//弹出1;
  alert(b);//不能获取b
//scope chain
  var a = 1;
  function test() {
    var b = 2;
    function test1() {
      var c = 3;
      alert(a);
      alert(b);
      alert(c);
    }
    test1();
  }
  test();//弹出1,弹出2,弹出3;
Copy after login

Lexical scope:


//词法作用域;
  function f1() {
    var a = 12;
    return f2();
  }
  function f2() {
    return a;
  }
  alert(f1());//并不能获取a,a在f2()中并未定义;
function f1() {
    var a = 1;
    return f2();
  }
  function f2() {
    var b = 3;
    alert(b);
    return a;
  }
  alert(f1());//弹出3,a在f2()中未定义

function f1() {
    var a = 1;
    return f2();
  }
  function f2() {
    var b = 3;
    alert(b);
    return a;
  }
  alert(f1());//弹出3,a在f2()中未定义,undefined
  var a=55;
  alert(f1());//弹出3,弹出55
Copy after login

How to break the global scope chain through closures - several common forms


//通过闭包突破全局作用域链
  function f() {
    var a = "sun";
    return function () {
      return a;
    }
  }
  var test = f();
  alert(test());//弹出sun
var n;
function f() {
  var a = "sun";
  n = function () {
    return a;
  }
}
f();
alert(n());//弹出sun
  function f(param) {
    var n =function () {
      return param;
    };
    param++;
    return n;
  }
  var test = f(45);
  alert(test());//弹出46;
Copy after login

The above is the detailed content of Detailed explanation of common forms of JS closures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template