2

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.

2 Answers 2

1

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;

    }

}(),
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Notice that const only means the variable doesn't change, not that the object it contains is not mutated (frozen).
@Bergi you're right. I removed the bit about const as I don't think it helped the discussion anyway. In a language like C++ you could make better guarantees about constness. In JS it's just a const reference, not a reference to a const :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.