I'm studying THREE.js and noticed a pattern where functions are defined like so:
var foo = ( function () {
var bar = new Bar();
return function ( ) {
//actual logic using bar from above.
//return result;
};
}());
(Example see raycast method here).
The normal variation of such a method would look like this:
var foo = function () {
var bar = new Bar();
//actual logic.
//return result;
};
Comparing the first version to the normal variation, the first seems to differ in that:
- It assigns the result of a self-executing function.
- It defines a local variable within this function.
- It returns the actual function containing logic that makes use of the local variable.
So the main difference is that in the first variation the bar is only assigned once, at initialization, while the second variation creates this temporary variable every time it is called.
My best guess on why this is used is that it limits the number of instances for bar (there will only be one) and thus saves memory management overhead.
My questions:
- Is this assumption correct?
- Is there a name for this pattern?
- Why is this used?