Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of returning a function from a function?

Tags:

javascript

Reading some legacy code, and found

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:

  1. why define setSize as a function which return another function
  2. Also the defined function is executed right away.

any light to shed on this?

Updated:

I can simply 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 snippet better than second?

like image 652
Adam Lee Avatar asked Aug 11 '15 23:08

Adam Lee


3 Answers

  1. So the returned function can access the value of v1 each time it is called without making v1 a global (or otherwise non-private)
  2. That is so the returned function is assigned to setSize
like image 178
Quentin Avatar answered Oct 16 '22 20:10

Quentin


It function closure. Used to hide variables from global scope. Read on and see some examples here

JS function closures

like image 23
Maksym Kozlenko Avatar answered Oct 16 '22 18:10

Maksym Kozlenko


The purpose in that particular case is to avoid creating a new Vector object each time setSize is called. It's a caching strategy. The alternative would be to just 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 closure cached version of setSize if I found I was having performance problems because of new Vector2().

like image 2
Kit Sunde Avatar answered Oct 16 '22 19:10

Kit Sunde