英文:
Javascript reference a function with a string (in a module)
问题
我有一个JS文件作为模块加载到头部:
<script type="module" src="/js/main.js"></script>
在main.js文件中,我有许多需要根据单击的按钮实例动态调用的函数。
通常的解决方法是使用window["my_func"]
,但在模块上下文中这不起作用。
我可以通过将每个函数分配给window来绕过这个问题,例如window.my_func = my_func;
,但我是否遗漏了什么?是否有类似于window["my_func"]
在模块范围内起作用的东西?
英文:
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?
答案1
得分: 1
你可以导入模块的命名空间对象,然后像你展示的那样使用它。所以,不要直接在script
标签中包含/js/main.js
,而是在script
标签中有另一个模块执行导入并按需调用函数:
import * as fns from "/js/main.js";
fns["my_func"]();
例如,假设你有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");
}
和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);
然后加载main.js
:
<script type="module" src="./main.js">
这将在10秒内每800毫秒调用functions.js
中的one
或two
之一。在 StackBlitz 上的示例(因为 Stack Snippets 不支持多个文件)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论