Why should I consider using JavaScript Closures in my code?

What are the advantages of using closures in JavaScript and why should I consider them in my code if I can write a simpler and simpler solution, at least in my opinion.

For example, consider the following:

    function multiplier(factor) {
       return function(number) {
          return number * factor;
       };
    }

    var twice = multiplier(2);
    console.log(twice(5));

      

//////////////////////////////////////////////// ////////////////

    function myMultiplier(factor, number) {
         return number * factor;
     }

    console.log(myMultiplier(2, 5)); 

      

They both output 10, but I find myMultipler is easier to understand, faster to write, and I only need one function. Why should I consider the version of the closure over my version?

Thanks in advance.

+3


source to share


3 answers


One of the typical scenarios in which closure might be required is for loops for

that register event handlers. The loop for

does not create a new area. This means that if you register an event handler inside the loop that relies on the values ​​of local variables as the loop goes through, you need a closure to carry the values ​​with the handler.

Consider the following two snippets. Someone without a closure will lead to unexpected results.

No closure



for(var i = 0; i < locations.length; i++){
    var marker = new google.maps.Marker(...);
    ...
    google.maps.event.addListener(marker, 'click', function(){
        ...
        // At the time of click the for loop has finished.
        // Thus, marker will be the last marker that was created in the loop.
    });
}

      

Closing

for(var i = 0; i < locations.length; i++){
    var marker = new google.maps.Marker(...);
    ...
    google.maps.event.addListener(marker, 'click', (function(marker){
        return function() {
            ...
            // The marker object is wrapped in the closure and
            // will possess the correct value
        }
    })(marker)); // Pass in marker to make the closure work
}

      

+3


source


The code in your question only shows "what is a closure" and is equivalent to writing a "hello world" application.

Closure allows you to transfer not only data, but also logic. This increases the reuse of some parts of the code:

var arr = [81,55,75,5,3,6,95,0,55,-97];

var sorter = function(modifier) {
    return function(arr){
        arr.sort(modifier);
    };
};

var asc = sorter(function(a,b){
   return a > b; 
});

var desc = sorter(function(a,b){
   return a < b; 
});

asc(arr);
console.log(arr);

desc(arr);
console.log(arr);

      

Output:



[-97, 0, 3, 5, 6, 55, 55, 75, 81, 95]
[95, 81, 75, 55, 55, 6, 5, 3, 0, -97] 

      

See: http://jsfiddle.net/jimschubert/7nnycrfj/

edit: you can see how reuse works by adding arrays of different types: http://jsfiddle.net/jimschubert/7nnycrfj/1/

+2


source


If you can write a simpler, more straightforward solution, do it that way. Speak javascript or say whatever.

Just because a function is there does not mean you should use it. You must use it if it serves your purpose. You shouldn't use closure in this case as you point out.

BUT CLOSES are not useless at all. They are the main feature of many programming languages. You can look at any documents about them to get what is useful to them. Here, for example.

-3


source







All Articles