Javascript 从JS中导入的模块内部启动本地函数
我试图运行一个本地函数,但我想从导入的模块内部启动它。这将是一个如何工作的草图。。。有什么建议吗 index.jsJavascript 从JS中导入的模块内部启动本地函数,javascript,Javascript,我试图运行一个本地函数,但我想从导入的模块内部启动它。这将是一个如何工作的草图。。。有什么建议吗 index.js import { runBar } from "myModule.js"; runBar(); function foo() { console.log('foo should run whenever bar is executed'); } import { runBar } from "myModule.js"; runBar(foo); function
import { runBar } from "myModule.js";
runBar();
function foo() {
console.log('foo should run whenever bar is executed');
}
import { runBar } from "myModule.js";
runBar(foo);
function foo() {
console.log('foo should run whenever bar is executed');
}
myModule.js
export function runBar(){
bar();
}
function bar() {
console.log("bar is running...");
//I want to call foo from here...
}
export function runBar(foo){
bar(foo);
}
function bar(foo) {
console.log("bar is running...");
//I want to call foo from here...
foo();
}
作为参数传递
foo
怎么样
index.js
import { runBar } from "myModule.js";
runBar();
function foo() {
console.log('foo should run whenever bar is executed');
}
import { runBar } from "myModule.js";
runBar(foo);
function foo() {
console.log('foo should run whenever bar is executed');
}
myModule.js
export function runBar(){
bar();
}
function bar() {
console.log("bar is running...");
//I want to call foo from here...
}
export function runBar(foo){
bar(foo);
}
function bar(foo) {
console.log("bar is running...");
//I want to call foo from here...
foo();
}
您不能从
bar
调用foo
,因为foo
不在范围内
要运行foo
,您可以选择:
runBar
,并让runBar
将其传递给bar
;或foo
并让myModule.js
导入它(循环依赖关系可以);或foo
成为全局(globalThis.foo=function foo(){/*…*/}
,或者可能使用window
而不是globalThis
),但我不建议这样做您还需要将它从
runBar
传递到bar
@T.J.Crowder-nice-catch!这正是你应该做的。