Search code examples
javascriptes6-modules

Javascript reference a function with a string (in a module)


I have a JS file loaded into the head as a module:

<script type="module" src="/js/main.js"></script> 

In the main.js file I have a number of function that need to be called dynamically, depending on what instance of a button is clicked.

The normal solution would be to use window["my_func"] but this doesn't work in a module context.

I can get around this by assigning each function to the window i.e window.my_func = my_func; but is there something I'm missing here? Is there something similar to window["my_func"] that works in the module scope?


Solution

  • You can import the module namespace object, then use it as you've shown. So instead of including /js/main.js directly in a script tag, have another module in the script tag that does the import and calls the functions as needed:

    import * as fns from "/js/main.js";
    
    fns["my_func"]();
    

    For example, suppose you had functions.js:

    function show(msg) {
        const p = document.createElement("p");
        p.textContent = msg;
        document.getElementById("output").appendChild(p);
    }
    export function one() {
        show("Function one called");
    }
    export function two() {
        show("Function two called");
    }
    

    and main.js:

    import * as fns from "./functions.js";
    
    const timer = setInterval(() => {
        const fn = Math.random() < 0.5 ? "one" : "two";
        fns[fn]();
    }, 800);
    setTimeout(() => {
        clearInterval(timer);
    }, 10000);
    

    And you loaded main.js:

    <script type="module" src="./main.js">
    

    That would call either one or two from functions.js once every 800ms until 10 seconds had passed. Example on stackblitz (since Stack Snippets don't support multiple files).