Error in GLTFloader through this.scene.add()

Hello,
I’m new to threeJS, but trying to learn.
I have this code saved in App.js

class App {

    init() {
        this.renderer = new WebGLRenderer( { alpha:true,antialias: true } );
        this.renderer.setPixelRatio( window.devicePixelRatio );
        this.renderer.outputEncoding = sRGBEncoding;
        this.renderer.shadowMap.enabled = true;

        this.scene = new Scene()
        this.camera = new PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 5000 );
        this.clock = new Clock()

        const loader = new GLTFLoader();
        loader.load(        'https://rawcdn.githack.com/mrdoob/three.js/7249d12dac2907dac95d36227d62c5415af51845/examples/models/gltf/Flamingo.glb',
            function ( gltf ) {        
                this.scene.add( gltf.scene );
            }
        )

I get this error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘scene’)
I know this is something with the scope but could not figure this out:/
Please help

Try changing it to an arrow function:

const loader = new GLTFLoader();
        loader.load(        'https://rawcdn.githack.com/mrdoob/three.js/7249d12dac2907dac95d36227d62c5415af51845/examples/models/gltf/Flamingo.glb',
             ( gltf ) => {        
                this.scene.add( gltf.scene );
            }
        )

perfect. thanks @panda_warrior !!

1 Like