是否可以导出调用模块导入文件中定义的另一个函数的函数?
Is it possible to export a function that calls another function defined in the file where the module is imported from?
示例:
// module "my-module.js"
export default function func1() {
...
func2();
...
}
其中 func2 仅在我们执行的文件中可用:
import func1 from './my-module.js'
function func2() {
console.log('OK');
}
func1();
这可能吗?
不行,创建func1
时必须定义func2
,否则会是undefined
,调用func1
时会抛出运行时异常。
您可以将 func2
作为 func1
的参数传递并在内部调用它。
// module "my-module.js"
export default function func1(callback) {
callback();
}
import func1 from './my-module.js';
function func2() {
console.log('OK');
}
func1(func2);
示例:
// module "my-module.js"
export default function func1() {
...
func2();
...
}
其中 func2 仅在我们执行的文件中可用:
import func1 from './my-module.js'
function func2() {
console.log('OK');
}
func1();
这可能吗?
不行,创建func1
时必须定义func2
,否则会是undefined
,调用func1
时会抛出运行时异常。
您可以将 func2
作为 func1
的参数传递并在内部调用它。
// module "my-module.js"
export default function func1(callback) {
callback();
}
import func1 from './my-module.js';
function func2() {
console.log('OK');
}
func1(func2);