Search code examples
typescriptbabylonjs

Typescript Pass Inline Void Function Error


I have got a question about TypeScript and Functions as Arguments. I had the problem with BabylonJS but I think, it is about all TypeScript. I am storing the render function in my class:

this._renderloop = newScene.render; // render(): void; is a function of BabylonJS.Scene class

and call the BabylonJS renderLoop via

this._webglEngine.runRenderLoop(this._renderloop);

This is giving me errors about some properties (e.g. _activeParticles) of Scene not being initialized.

But when I am setting the renderloop via:

this._renderloop = () => newScene.render();
this._webglEngine.runRenderLoop(this.renderloop);

everything is working fine.

What is the problem with the first call? Wouldn't the second be more performant, because I skips one function call?

(BabylonJS Docs can be found here: https://doc.babylonjs.com/)


Solution

  • this._webglEngine.runRenderLoop(newScene.render)
    

    The this inside scene.render will be undefined. The easiest way to fix it is to wrap it in a function like your second example.

    This is because of the way javascript handles this. There's a nice guide on using this in the Typescript wiki.