Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从JS中导入的模块内部启动本地函数_Javascript - Fatal编程技术网

Javascript 从JS中导入的模块内部启动本地函数

Javascript 从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

我试图运行一个本地函数,但我想从导入的模块内部启动它。这将是一个如何工作的草图。。。有什么建议吗

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();
}

作为参数传递
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!这正是你应该做的。