SoFunction
Updated on 2025-03-06

Detailed explanation of js closure usage example

This article describes the usage of js closures. Share it for your reference, as follows:

introduction

In the company, you need to write a js script to perform website statistics and implement functions similar to Baidu statistics or webmaster statistics. During the implementation process, you feel that the code you wrote is still OK, because the previous js code was written, but when the group leader checked the code, I was very dissatisfied with the group leader's code, because the methods we wrote in js are all global methods. Because the things we wrote need to be embedded in other people's interfaces, these global things may be duplicated with other people's things, which will cause errors. So the group leader left me a sentence: wrap it with js closure.

Variable scope

We are all very familiar with the scope of variables, which are divided into: global variables and local variables. In js, global variables can be read directly inside the function.

Js code

var n=999;
function f1(){
  alert(n);
}
f1(); // 999

On the other hand, local variables inside the function are naturally not read outside the function.

Js code

function f1(){
  var n=999;
}
alert(n); // error

We also need to note that if you declare a variable in js, you must use the var command, otherwise a global variable is actually declared!

function f1(){
  n=999;
}
f1();
alert(n); // 999

How to read global variables from outside?

What should we do if we need to get the global variables inside the function? . Under normal circumstances, we cannot do it. To implement this, we must think of some ways - define a function inside the function:

function f1(){
  n=999;
  function f2(){
    alert(n); // 999
  }
}

In the above code, function f2 is included inside function f1, and all local variables inside f1 are visible to f2. But the other way around is not possible. Local variables inside f2 are invisible to f1. This is the "chain scope" structure unique to JavaScript language. The child objects will look upwards level by level to level for all parent objects variables. Therefore, all variables of the parent object are visible to the child object, otherwise it is not true.

Since f2 can read local variables in f1, as long as f2 is used as the return value, can't we read its internal variables outside f1?

function f1(){
  n=999;
  function f2(){
    alert(n);
  }
  return f2;
}
var result=f1();
result(); // 999

Concept of closure

In the above code, the f2 function is the closure. The definition of "closure" in various professional documents is very abstract and difficult to understand. My understanding is that a closure is a function that can read variables inside other functions. Since in Javascript language, only subfunctions inside functions can read local variables, closures can be simply understood as "functions defined inside a function". So, in essence, a closure is a bridge connecting the inside and the outside of the function.

Let’s share the writing method of the js closure we used in the project:

(function () {
  function getPageTitle() {
    return ;
  }
  function getBrowerLanguage() {
    var browerLanguage = ! ?  : ;
    return browerLanguage;
  }
  /**
    * The part after the current page address #
    */
  function getLastUrl() {
    var url = ;
    if (!url) {
      return null;
    }
    else {
      return ().split("#")[1];
    }
  }
  function GetRandomNum() {
    var arr = (new RegExp("(^| )" + "statisticssCookie=([^;]*)(;|$)"));
    if (arr != null) {
      return arr[2];
    } else {
      var tempRandomNum = guid();
       = "statisticssCookie = " + tempRandomNum;
      return tempRandomNum;
    }
  }
  function guid() {
    function S4() {
      return (((1 + ()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }
  function addJs() {
    var url = "http://localhost:10086/tongji/tongji/do?title=" + getPageTitle() + "&browerLanguage=" + getBrowerLanguage() + "&lastUrl=" + getLastUrl() + "&upFlag=" + GetRandomNum();
    var head = ('head')[0];
    var js = ('script');
     = 'text/javascript';
     = url;
    (js);
  }
   = addJs;//Hang the addJs method under the window, so that it can be accessed by the outside world, otherwise the outside world will never be able to access the method I wrote.   = addJs();//Execute after the DOM tree is loaded})(window)

summary

At the beginning, the team leader asked me if I could do js closure function, because if I didn’t have closures, I couldn’t write good code. The code we write is very rough, so when we write code, we cannot just meet the function implementation, and we need to consider some other aspects. Of course, js closures also have some disadvantages when using them, so we also need to consider comprehensive and comprehensive information when using them.

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills"and"JavaScript traversal algorithm and skills summary

I hope this article will be helpful to everyone's JavaScript programming.