简体   繁体   中英

Exporting multiple functions with arguments

All I am trying to do is to export two functions from a module. One function taking an argument and the other with no argument:

function initClass(params)
{
   return new Promise( (resolve, reject) => {
        if (!wallet) {
            wallet = new WalletClient(params);
            resolve(wallet);
        } else {
            console.log('Wallet is initialized');
            resolve(wallet);
        }
});
}

function getInstance()
{
   return wallet;
}

For initClass(params) only, I can do this as:

module.exports = (params) => {
   initClass(params)
}

And then I call this as:

var init = require('./class.js')(params).initClass(params);

This works fine.

Now, for me to export getInstance() as well, I have tried to do the following but it doesn't seem to work.

module.exports = (params) => {
   initClass(params),
   getInstance
}

This complaints that there is no function getInstance .

Then I tried this:

module.exports.init = (params) => {
   initClass(params)
}

module.exports.instance = {
   getInstance
}

Then call them as:

var init = require('./class.js').init(params).initClass(params);

What is the proper way to export multiple functions like this? Thank you.

If i'm understanding correctly you are trying to export multiple methods if that is the case simple use this.

   module.exports = {
        method: function() {},
        otherMethod: function(parmas) {}
    }

In your code use like this.

 var init = require('./class.js');
    init.method()
    init.otherMethond(paramObj)

If you want below scenario you need to check out about method chaining.

var init = require('./class.js').init(params).initClass(params);

You're making it more complex than needed. Once you have your functions defined, you can export it with this:

module.exports = {
  initClass,
  getInstance
}

To use it, you do this:

const init = require("./class.js");
init.initClass(params);
const instance = init.getInstance();

What you're exporting from the module is an object (which I've named init in the example above) that contains two functions. You don't have to pass arguments to the functions at the time you require .

module.exports is basically an object with keys which can refer to any variables/functions of your file.In your case,

module.exports.initClass = function (params){
...
}

module.exports.getInstance = function (){
}

When importing it

var init = require('./class.') // init object has two keys -> initClass and getInstance
 init.initClass('abc')
 init.getInstance()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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