'How to keep the reference from Three.js object after loading in an .obj?

The official docs has a pretty good example of how to add a .obj file to a scene.

const loader = new OBJLoader();

// load a resource
loader.load(
    // resource URL
    'models/monster.obj',
    // called when resource is loaded
    function ( object ) {

        scene.add( object );

    },
    // called when loading is in progresses
    function ( xhr ) {

        console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

    },
    // called when loading has errors
    function ( error ) {

        console.log( 'An error happened' );

    }
);

However, I am not sure how I would now go about manipulating the loaded object. The URL is used to load the object and then the loaded object is passed as the argument to the on load function, i.e., the first nameless function passed to loader.load. However, what would be the 'best' way to retain a reference to that object?



Solution 1:[1]

The one way I can manage does not seem great, but it works.

I could simply bind it to the current window or document:

function ( object ) {
    scene.add( object ); 
    window.obj = object; // binding it to the window
}

But this seems a little odd to me as this would bind it to global space. What if I wanted to keep the scope more contained, for example?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mitchell van Zuylen