【问题标题】:Call a function from the same `module.exports` object by it name [duplicate]按名称从同一个`module.exports`对象调用一个函数[重复]
【发布时间】:2015-11-01 15:28:45
【问题描述】:

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

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

};

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    用对象名调用它:

    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');

    【讨论】:

    • 你也可以做 ``` module.exports = { a() { console.log('a') }, b() { console.log('b') }, c( fn) { fn() } } ``` 并在另一个文件中调用它,例如 var func = require('./func.js') func.c(func.a)
    • @Jekrb,我不明白。
    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2014-03-09
    • 2020-04-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多