通过名称从相同的`module.exports`对象调用函数

zia*_*war 2 javascript node.js

我需要module.export通过只知道它的string名称来调用对象中 的函数

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]()`
  }

};
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 6

使用对象名称调用它:

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');
Run Code Online (Sandbox Code Playgroud)