简体   繁体   中英

Unused Functions Not Recognized In Window

Working in ReactJS, I run into an issue where imported functions that are 'unused' are failing to be recognized by the program and I believe are not being added to the window.

In my case, I'm trying to be able to import functions from other files and then call them by string name.

Ex)

import {myFunction} from '../otherFile';

functionNameString = 'myFunction'
window[functionNameString]()       //call function by it's string name

//ERROR: window[functionNameString] is not a function

Without changing my above syntax, I've found two ways I can resolve this:

  1. Add the actual function to the same file as the window[functionNameString]() call
  2. Explicitly assign the function to the window at the top of my file like window.myFunction = myFunction

I'm trying to avoid the first case to keep this file shorter, but also don't understand why I need to do the explicit assignment of the function to the window as shown in the second case (and why defining the function in the same file doesn't need this)

Overall, my question is how can I avoid this explicit assignment of and have these imported functions callable from import (or in a shorter syntax)? Assigning like so is fine for a function or two, but I'm looking at importing 15 funcs from this other file which makes things messy working in this fashion. Thanks!

Modules have their own scope, they aren't at global scope, and imports are created as bindings within the module scope, not globals. That's at least half the point of modules: to not make everything global anymore.

Overall, my question is how can I avoid this explicit assignment of and have these imported functions callable?

They are callable. myFunction() will call your function in your example code. There's no reason whatsoever for window to be involved.

If you need to refer to them by a name in a string for some reason, you can put them in an object:

const functions = {
    myFunction,
    // ...
};

Then functions[functionNameString]() will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM