SoFunction
Updated on 2025-04-07

Learn Javascript closures easily

Closure is a difficulty in the Javascript language and its feature. Many advanced applications rely on closures to implement.

When a function is nested in a function, the internal function can access variables in the external function.

function foo(x) {
 var tmp = 3;
 function bar(y) {
  alert(x + y + (++tmp));
 }
 bar(10);
}
foo(2)

No matter how many times it is executed, it will alert 16, because bar can access the parameter x of foo and also access the variable tmp of foo.

But, this is not a closure. When what you return is an internal function, it is a closure. The internal function closes-over the external function variable until the internal function ends.

function foo(x) {
 var tmp = 3;
 return function (y) {
  alert(x + y + (++tmp));
 }
}
var bar = foo(2); // bar is now a closurebar(10);

The above script will eventually alert 16, because although bar is not directly in the internal scope of foo, bar can still access x and tmp.

However, since tmp still exists inside the bar closure, it will still add 1 by itself, and every time you call bar, it will add 1 by itself.

(Considering the six-year-old limitation: we can actually build more than one closure method, such as returning their arrays, or set them as global variables. They all point to the same x and the same tmp instead of having a copy of each.)

Note: Let’s take a look at the seven-year-old content now.

The above x is a literal value (value passing), just like other literal values ​​in JS. When foo is called, the value of the actual parameter x is copied, and the copied copy is used as the parameter x of foo.

So the problem is that when processing object in JS, referential pass is used. Then, when you call foo, the closure of the return foo function will also refer to the original object!

function foo(x) {
var tmp = 3;
return function (y) {
 alert(x + y + tmp);
  =  ?  + 1 : 1;
 alert();
 }
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure that references agebar(10);

As expected, every time we run bar(10), 1 will be added to it. But it should be noted that x points to the same object variable - age every time. After running bar(10) twice, it will become 2.
This is related to the memory leak of HTML objects, uh, but it seems to be beyond the scope of answering questions.

Here is an example of a closure without the return keyword:

function closureExample(objID, text, timedelay) { 
  setTimeout(function() { 
    (objID).innerHTML = text; 
  }, timedelay); 
} 
closureExample(‘myDiv', ‘Closure is created', 500); 

Functions in JS can access them:

1. Parameters

2. Local variables or functions

3. External variables (environment variables?), including

3.1 Global variables, including DOM.

3.2 Variables or functions of external functions.

If a function accesses its external variable, it is a closure.

Note that external functions are not required. By accessing external variables, a closure can keep these variables alive. In the example of internal functions and external functions, the external function can create local variables and eventually exit; however, if any one or more internal functions do not exit after it exits, the internal function maintains the local data of the external function.
A typical example is the use of global variables.

Closures are often used to create functions that contain hidden data (but not always).

var db = (function() {
// Create a hidden object, which holds some data// This object cannot be accessed from the outsidevar data = {};
// Create a function, which provides some methods to access data datareturn function(key, val) {
  if (val === undefined) { return data[key] } // get
  else { return data[key] = val } // set
  }
// We can call this anonymous method// Return this internal function, it is a closure})();
db('x'); // Return undefineddb('x', 1); // Set data['x'] to 1db('x'); // Return 1// We cannot access the object itself// But we can set its members

Let's take a look at the points of using closures

1) Since closures will cause all variables in the function to be stored in memory, and the memory consumption is very large, closures cannot be abused, otherwise it will cause performance problems of the web page and may lead to memory leakage in IE. The solution is to delete all local variables that are not used before exiting the function.

2) The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its public method, and use the internal variable as its private property, be careful not to change the value of the internal variable of the parent function at will.

The above is the Javascript closure knowledge introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!