2

I need to call a function within the module.export object by knowing only it string name

module.exports = {

  a : function() { console.log('a'); },

  b : function() { console.log('b'); },

  c : function() {
    var fn; // string contain the name of the function to call ('a' or 'b' for example)

    // How do I call `fn` programatically from here?
    // something like `self[fn]()`
  }

};
zianwar
  • 3,642
  • 3
  • 28
  • 37

1 Answers1

6

Call it with the object name:

var module = {
    exports: {
        a: function () { alert('a'); },
        b: function () { alert('b'); },
        c: function (fn) { // string contain the name of the function to call ('a' or 'b' for example)
            module.exports[fn]();
        }
    }
};
module.exports.c('b');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • also you could do ``` module.exports = { a() { console.log('a') }, b() { console.log('b') }, c(fn) { fn() } } ``` and in another file you call it like var func = require('./func.js') func.c(func.a) – Jekrb Aug 09 '15 at 18:27
  • 1
    @Jekrb, i do not understand. – Nina Scholz Aug 09 '15 at 19:15