What is the purpose of returning a function from a function?

Reading some legacy code and discovering

A.prototype.setSize: function () { var v1 = new Vector2(); return function (size ) { var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); this.min.sub( halfSize ); return this; }; }(), 

I am wondering:

  • why define setSize as a function that returns another function
  • Also, a specific function is executed immediately.

Any light to shed on this?

Updated:

I can just use

  A.prototype.setSize: function (size) { var v1 = new Vector2(); var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); this.min.sub( halfSize ); return this; }, 

Is the first fragment better than the second?

+4
source share
4 answers
  • Thus, the returned function can access the value of v1 with every call, without making v1 global (or otherwise not closed)
  • Thus, the returned function is assigned setSize
+5
source

The goal in this particular case is to avoid creating a new Vector object each time setSize is setSize . This is a caching strategy. An alternative would be to simply have a flat function:

 A.prototype.setSize: function (size) { var v1 = new Vector2(); var halfSize = v1.copy(size).multiplyScalar(0.5); this.min.sub(halfSize); return this; } 

I would only use the closed cached version of setSize if I found that I had performance issues due to new Vector2() .

+2
source

Classic example:

 function createAdder(x) { return function add(y) { return x + y; } } var addTwo = createAdder(2); // addTwo is a function that takes one input and adds 2 to it addTwo(3); // 5 addTwo(9); // 11 

The idea is that you want to create a function, but the function you want to create depends on something. In this case, we wanted to create the addX function.

See Chapter 5 of Eloquent Javascript for more details. In particular, the section of higher orders .


It may also be drier. Consider:

 function createSecretAdder() { var secretNumber = generateSecretNumber(); // THIS TAKES A LONG TIME return function(n) { return secretNumber + n; } } var secretAdder = createSecretAdder(); // slow secretAdder(2); // fast secretAdder(7); // fast 

vs.

 function createSecretAdder() { return function(n) { var secret = getSecretNumber(); // THIS TAKES A LONG TIME return secretNumber + n; } } var secretAdder = createSecretAdder(); // fast secretAdder(2); // slow secretAdder(7); // slow 

The first is DRYer and faster than the last. This should concern your comment and update to your question.

Note: you need to understand closures to understand how this works.


For the reason for calling him immediately, see here .

+2
source

This is a function closure. Used to hide variables from the global scope. Check out some examples here.

Closing JS Functions

+2
source

All Articles