简体   繁体   English

Window 中未识别的未使用功能

[英]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.在 ReactJS 中工作时,我遇到了一个问题,即“未使用”的导入函数无法被程序识别,并且我相信没有被添加到 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将实际的 function 添加到与window[functionNameString]()调用相同的文件中
  2. Explicitly assign the function to the window at the top of my file like window.myFunction = myFunction将 function 显式分配给我文件顶部的 window,例如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)我试图避免第一种情况以使该文件更短,但也不明白为什么我需要将 function 显式分配给 window,如第二种情况所示(以及为什么在相同的情况下定义 ZC1C425268E68384F14AZ0文件不需要这个)

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.像这样分配对于 function 或两个来说很好,但我正在考虑从另一个文件中导入 15 个函数,这会使事情以这种方式工作变得混乱。 Thanks!谢谢!

Modules have their own scope, they aren't at global scope, and imports are created as bindings within the module scope, not globals.模块有自己的 scope,它们不在全局 scope 中,并且导入是作为模块 scope 中的绑定创建的,而不是全局的。 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. myFunction()将在您的示例代码中调用您的 function。 There's no reason whatsoever for window to be involved. window没有任何理由参与其中。

If you need to refer to them by a name in a string for some reason, you can put them in an object:如果出于某种原因需要在字符串中通过名称来引用它们,可以将它们放在 object 中:

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

Then functions[functionNameString]() will work.然后functions[functionNameString]()将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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