简体   繁体   English

如何通过导出导出功能相同但参数不同的功能

[英]How to export the same function but with different parameters by export

I need to export the same pre-defined function, but with different parameters by export. 我需要导出相同的预定义函数,但导出时使用不同的参数。

What I'm trying to achieve: 我想要达到的目标:

module.exports = {
    adminSaysHello: sayText("Hello", "admin"),
    adminSaysText: sayText(text, "admin"),
    sayText: sayText
}

function sayText(text, author){
    console.log(`${author} said: ${text}`);
}

module.adminSaysHello();
module.adminSaysText("Good Bye");
module.sayText("Hello, my name is Foo", "Foo");

When executing above script I get the following error: 执行上述脚本时,出现以下错误:

    adminSaysText: sayText(text, "admin"),
                           ^

ReferenceError: text is not defined

How to do this export correctly? 如何正确导出?

You should make use of closure functionality in JavaScript to make it work. 您应该利用JavaScript中的闭包功能使其正常工作。 Try this 尝试这个

 module.exports = { adminSaysHello: sayText("Hello", "admin"), adminSaysText: sayText(text, "admin"), sayText: sayText } function sayText(text, author){ return function(){ console.log(`${author} said: ${text}`); } } module.adminSaysHello(); module.adminSaysText("Good Bye"); module.sayText("Hello, my name is Foo", "Foo"); 

You'll need to create additional functions which then call the original function with specific parameters. 您需要创建其他函数,然后使用特定的参数调用原始函数。 That will look something like this: 看起来像这样:

module.exports = {
    adminSaysHello: () => sayText('Hello', 'admin'),
    adminSaysText: (text) => sayText(text, 'admin'),
    sayText: sayText
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM