Analysis of the situation and advantages and disadvantages of the js closure

  • 2020-06-19 09:41:03
  • OfStack

First, the above code:


// function a
function a()
{
var i=0;
// function b
function b()
{
alert(++i);
}
return b;
}
// function c
var c = a();
c();

Code features:

1. Function b is nested inside the function a;
2. a returns b.
When b, the inner function of a, is referenced by the variable c outside of a, a closure is created. Sometimes the function b can be returned with an anonymous function, return function(){};

Advantages: 1. Protect the variable security within the function, and strengthen encapsulation; 2. Maintain a variable in memory (too much of it becomes a disadvantage, occupying memory)
The reason closures take up resources is that the variable i is not destroyed at the end of the function a because the execution of b depends on the variable in a.
Not suitable scenario: The function that returns the closure is a very large function

A typical framework for closures would be jquery.

Closures are one of the main features of the javascript language, and they are used mainly to design proprietary methods and variables.
This is especially true in frameworks where some methods and properties are only used in the logic of operations and you don't want to have them modified externally, so you can design a closure that only provides method fetching.

The disadvantage of closures is that they can be resident in memory, increase memory usage, and can easily leak memory if used improperly.

Conclusion 1:

Advantages:

1. Logical continuity. When a closure is used as an argument to another function call, it prevents you from writing extra logic separately from the current logic.
2. Local variables that facilitate the invocation context.
3. Strengthen encapsulation. The extension of point 2 can achieve the protection of variables.

Disadvantages:

One of the most serious problems with closures is that they waste memory, not only because they are resident in memory, but more importantly, because they are improperly used, they create invalid memory. See the following example:


var array = [];
function abc() {
var foo = function(){
}
array.push(foo);
return foo;
}
for(var i = 0 ; i < 10000; i ++)
{
abc();
}

alert(array[0] == array[1]);

Through the above test we will see the 10000 times abc () to perform the closure with a logical address is not the same, that is to say, it produced 1 stack mold 1 sample Function object, so that is good is produced in factory pattern function for use, but if you use will be affected by any carelessness closure as normal logic, will inevitably cause memory garbage. It might be easier to understand by changing the syntax:


var foo = new Function();

So with closures, as far as I'm concerned, I don't use them if I can, and if I have to, I try to keep the number of closure objects small or even one.

This is the end of this article, I hope you enjoy it.


Related articles: