0

I have a function that is imported like this:

import { myFunc } from './myFunc.js';

I am trying to run this function using a string as the function name (the contents of the string may change):

let fnStr = "myFunc";
let fn = window[fnStr];
fn();

However, window[fnStr] cannot find the imported function.

JoeTidee
  • 24,754
  • 25
  • 104
  • 149

1 Answers1

1

You don't, because they aren't properties of the global object (which is referenced via window on browsers). They aren't globals at all. Which is a Good Thing.™ :-)

You could create your own object with those functions on it, and use it instead:

import { myFunc } from './myFunc.js';

const funcs = {
    myFunc
};

Usage:

let fnStr = "myFunc";
let fn = funcs[fnStr];
fn();

If you have several of these functions, you might want to export them on an object rather than as individual bindings, e.g.:

myFuncs.js:

function myFunc() {
    // ...
}
function myOtherFunc() {
    // ...
}

export default {myFunc, myOtherFunc};

then

import funcs from './myFuncs.js';

let fnStr = "myFunc";
let fn = funcs[fnStr];
fn();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875