Potentially silly javascript question...

42 views
Skip to first unread message

Mark Sibly

unread,
Mar 30, 2022, 8:34:41 PM3/30/22
to emscripten-discuss
Hi,

I'm a little confused by this code in index.html:
```
canvas: (function() {

        var canvas = document.getElementById('canvas');
        canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);

        return canvas;
    })(),
```
What's the deal with the weird `(function(){...})();` syntax? Other functions in index.html don't seem to do this.

Is it something to do with only running the function code once? Otherwise it seems like a weglcontextlost listener would be added each time canvas() was called!

Bye,
Mark

Mark Sibly

unread,
Mar 31, 2022, 3:19:29 AM3/31/22
to emscripten-discuss
Ok, I think I get it, 'canvas' will end up bound to the value returned by the function call, not the function itself so it is indeed a way to call an 'init' function once! Is that about right?

Leonardo Campos

unread,
Apr 2, 2022, 3:16:18 AM4/2/22
to emscripten-discuss
That is called "Immediately Invoked Function Expression" (IIFE) and as you said "canvas" will receive the value returned by that function. You can find more information about how it works at https://developer.mozilla.org/en-US/docs/Glossary/IIFE.
Reply all
Reply to author
Forward
0 new messages