0

In three.js source, there are multiple usage of this pattern. It seems that taking out the IIFE will not make any difference. My guess is that a named function is perfered over an anonymous function.

https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js

Object.assign( THREE.Object3D.prototype, ..., {

    ...

    rotateX : function () {

        var v1 = new THREE.Vector3( 1, 0, 0 );

        return function rotateX( angle ) {
            return this.rotateOnAxis( v1, angle );
        };
    }(),

    ...

})
golopot
  • 10,726
  • 6
  • 37
  • 51
  • What would happen to `v1` if you took out the IIFE? It *does* make a difference. – Bergi Jul 23 '16 at 10:23
  • http://benalman.com/news/2012/09/partial-application-in-javascript/ – Andreas Jul 23 '16 at 10:26
  • possibly related: [the three.js sources might be a mess](http://stackoverflow.com/q/21533862/1048572) – Bergi Jul 23 '16 at 10:27
  • The reason for the IIFE pattern is for performance. Note that `rotateX` in your example does not need to instantiate a new `v1` vector every time `rotateX` is called, but rather puts it in a closure to be used repeatedly. If rotateX is called many times, it does not waste time and memory instantiating and then garbage collecting a variable which is essentially acting as a constant. It also provides privacy due to the closure. – Brendan Annable Jul 24 '16 at 00:31

1 Answers1

0

It creates a closure, giving the function access to the value of v1 without putting the v1 variable in a scope any wider than necessary.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335