Reputation: 1166
Inside Object3D
you can see:
rotateX: function () {
var v1 = new THREE.Vector3( 1, 0, 0 );
return function ( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
Why not:
rotateX: function (angle) {
var v1 = new THREE.Vector3( 1, 0, 0 );
this.rotateOnAxis( v1, angle );
},
(or something similar, that is, a pure 'direct' function.)
I know this is a pure JavaScript question but I'm curious. Thanks.
Upvotes: 2
Views: 87
Reputation: 104783
This other answer is somewhat misleading.
The fact that v1
does not change is irrelevant.
The only reason the function is written this way is to prevent the Vector3
object from being instantiated (and later garbage-collected) every time the function is called.
As written, v1
is instantiated only once, and can be reused.
Here is another example from the Object3D
class that uses the same pattern. Notice that the variable q1
inside the closure is, in fact, changed in this case.
rotateOnAxis: function () {
// rotate object on axis in object space
// axis is assumed to be normalized
var q1 = new THREE.Quaternion();
return function ( axis, angle ) {
q1.setFromAxisAngle( axis, angle );
this.quaternion.multiply( q1 );
return this;
}
}(),
Upvotes: 1
Reputation: 310852
Because the value of v1
doesn't change (it's the unit vector along the x-axis) there's no point to allocate it and then garbage collect it every time the function is called.
Instead, it's captured inside a function to ensure that it's not possible to modify it. This pattern is sometimes called an immediate function.
Note that the outer function is executed when rotateX
is defined, and its value is assigned as the inner function. This inner function closes over the unchangeable value of v1
.
Upvotes: 1