In which scenario would you use a function that returns another function (Javascript)?

Thanks to this question, I understand how a function can take two sets of parentheses and how a function can return another function that fires immediately after it returns.

I do not understand why it is good to know? How can this be applied to solve a problem?

Example:

function add(x){ return function(y){ return x + y; }; } add(3)(4) === 7; // true 

It works well. But why not just write it like this?

 function add(a, b) { return a + b; } add(3, 4) === 7; // true 
+5
source share
7 answers

Let's take the same code that you mentioned.

  function add(x) { return function(y) { return x + y; }; } var adder3 = add(3); //Forming adder3 var op1 = adder3(4) // 7 var op1 = adder3(5) // 9 // Now adder 10: var adder10 = add(10); //Forming adder3 var op1 = adder3(4) // 14 var op1 = adder3(5) // 15; 

I hope you understand !!

Bring me back if you need more information on closing.

+2
source

Your example is called closing

  • Closing Rules and Side Effects

  • Closures have access to the variable of external functions even after the return of the external function:

One of the most important and delicate functions with closure is that the inner function still has access to the outer functions, even after the outer function has returned. Yes, you read it right. When functions in JavaScript are executed, they use the same scope chain that acted when they were created. This means that even after the external function has returned, the internal function still has access to external functions. Therefore, you can call the internal function later in your program. This example demonstrates:

<i>

 function celebrityName(firstName) { var nameIntro = "This celebrity is "; // this inner function has access to the outer function variables, including the parameter​ function lastName(theLastName) { return nameIntro + firstName + " " + theLastName; } return lastName; }​​ var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.​​​ // The closure (lastName) is called here after the outer function has returned above​​ // Yet, the closure still has access to the outer function variables and parameter​ mjName("Jackson"); // This celebrity is Michael Jackson 

  1. Closing stores references to external variables of functions; they do not retain the actual value. Closing becomes more interesting when the value of a variable of external functions changes before the closure is called. And this powerful feature can be used for creative purposes, for example, this example of private variables, first demonstrated by Douglas Crockford:

<i>

 function celebrityID() { var celebrityID = 999; // We are returning an object with some inner functions​ // All the inner functions have access to the outer function variables​ return { getID: function() { // This inner function will return the UPDATED celebrityID variable​ // It will return the current value of celebrityID, even after the changeTheID function changes it​ return celebrityID; }, setID: function(theNewID) { // This inner function will change the outer function variable anytime​ celebrityID = theNewID; } }​ }​​ var mjID = celebrityID(); // At this juncture, the celebrityID outer function has returned.​ mjID.getID(); // 999​ mjID.setID(567); // Changes the outer function variable​ mjID.getID(); // 567: It returns the updated celebrityId variable 

Link: http://javascriptissexy.com/understand-javascript-closures-with-ease/

+1
source

Functions that return functions are useful when you need similar functions depending on some parameters.

Real-life example: [].sort can be called using a special comparator function, but it makes sense to define a comparator function to allow more settings:

 function comparator(options) { // Function which returns a function return function(a, b, tmp) { if(options.reverse) tmp = a, a = b, b = tmp; if(options.map) a = options.map(a), b = options.map(b); if(options.func) return options.func(a, b); return a < b ? -1 : (b < a ? 1 : 0); } } 

Then you can use

 [1,11,10,2].sort(comparator({map: String})); // [1, 10, 11, 2] [1,11,10,2].sort(comparator({reverse: true})); // [11, 10, 2, 1] [1,11,10,2].sort(comparator({func: Function.prototype})); // [1, 11, 10, 2] 
+1
source

if we need a function in a certain state with a certain value, we can use it inside another function and return it so that the return function with a certain state can be directly used in another scenario. You can check out various closing examples. http://javascriptissexy.com/understand-javascript-closures-with-ease/

+1
source

If you know that the first parameter will always be the same, then it will be convenient to close it, and not pass it over and over. For simple programs, this may not make sense. But for programs that process repetitive parameters more often, this method is definitely useful.

0
source

it makes no sense to use it immediately. you must use it to create a function to attach to an event or use as a callback for an asynchronous function. an example might be like this:

 function factory(param){ return function(result) { if (result==param) dosomething(); } } $('#domobject').click({ param = $('#domvalue').value; asynch_function(factory(param)); }); 

Here I added a click event, presumably a button. When it is pressed, it will receive the input value and create a function on it and will call the asynchronous function with the newly created function as a callback. An asynchronous function may be an ajax request. When the asynchronous function finishes executing the function created by the factory, a callback will be called. It will check the return value that the asynchronous function passed to the callback with respect to the parameter specified when the event was connected.

If we move the dom search inside the callback function, then we do not need a factory or param, but then it will use the value that is in the input when the asynch function returns, and than when the button was pressed later, and the value could change .

Sometimes you won’t be able to get the value you need in the callback context for other reasons. Or it may just be that you want to abstract away from the function class, so you do not need to re-enter a slightly different version in all places where you use it.

0
source

In addition to closures, you can also use it for pre-processing as a one-time job, think about whether you need to do something intense, for example. generate a million things;

 function generateSessionSecrets(lock) { var secrets = [], i = 1000000; while (i-- > 0) { secrets[i] = Math.random(); } return function(key, i) { if (key === lock) return secrets[i]; } } var chest = generateSessionSecrets('fizz'); chest('fizz', 0); // eg 0.2096199430525303 chest('fizz', 1); // eg 0.30329699837602675 // ... chest('fizz', 0); // still 0.2096199430525303 

(This is an example of a concept, not an example of real security)

0
source

Source: https://habr.com/ru/post/1238597/


All Articles