Zeromatiker Zeromatiker - 1 month ago 12
Javascript Question

Anvantage of self invoking function inside function definition

whats the advantage of a function definition like this:

obj = { func: function(){return function func(){return this.something;};}() }


Story:
I was looking for a way how to rotate a Three.js Vector3 by a certain angle around an axis and found this:
How to rotate a Three.js Vector3 around an axis?
I was interested in how the function works and looked it up: https://github.com/mrdoob/three.js/blob/master/src/math/Vector3.js. The function looks like this:

applyAxisAngle: function () {

var quaternion;

return function applyAxisAngle( axis, angle ) {

if ( quaternion === undefined ) quaternion = new Quaternion();

return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );

};

}(),


So whats the reason for this way of the defining a function?

Answer

The immediately-invoked function expression (IIFE) lets the author of that code give the applyAxisAngle function a truly private quaternion variable that nothing else anywhere can see.

That code basically does this:

var quaternion;

// ...

applyAxisAngle: function applyAxisAngle( axis, angle ) {

    if ( quaternion === undefined ) quaternion = new Quaternion();

    return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
},

...but keeping quaternion entirely private, rather than sharing it with code in the scope where all of this appears.

It defers constructing the Quaternion object until the first time it's called, and then it reuses that object in all subsequent calls by using the value from that private quaternion variable.

Comments