导出的函数将参数和常量传递给另一个函数



我真的不知道如何描述它,但我会尝试解释它。

我希望能够调用func1()func2(),但要在模块中调用handler()。我希望以这样的方式调用module.exported1("foo")将调用handler(func1, "foo"),进而调用func1("foo")。我遇到的问题是,如果我将"exported1"导出为handler(func1),我就无法传递调用exported1时使用的任何参数(据我所知(。有解决办法吗?

注意:这是一个模块,我需要将其导出,而无需用户提供func1func2handler()

function func1(args) {
...
}
function func2(args) {
...
}
function handler(func, args) {
return func()
}
module.exports = {
exported1 = handler(func1, ...),
exported2 = handler(func2, ...)
}

我不确定为什么要使用这种模式,但我相信代码中还有更多内容,我想你可以做以下操作:

function func1(args) {
console.info(`func1 ${args}`);
}
function func2(args) {
console.info(`func2 ${args}`);
}
function handler(func, args) {
return func(args);
}
module.exports = {
exported1: (args) => {
return handler(func1, (args));
},
exported2: (args) => {
return handler(func2, (args));
},
};

您只需要导出函数:

module.exports = {
exported = handler
}

或者,只是:

exports.exported = handler

现在,导入后,您可以使用参数调用:

exported(func1,...)
exported(func2,...)

看完你编辑过的问题后,我想你想做这样的事情,但我不太确定:

function handler(func) {
// you can replace it with function(args) { instead of arrow function
return (args) => {
return func(args)
}
}
module.exports = {
exported1 = handler(func1),
exported2 = handler(func2)
}
exported1(args)

最新更新