javascript - 通过名称从同一个 `module.exports` 对象调用一个函数

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

};

最佳答案

用对象名调用它:

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

关于javascript - 通过名称从同一个 `module.exports` 对象调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907317/

相关文章:

javascript - 如何使用嵌套属性在 AngularJS 中排序

javascript - 使用示例数据重新排列 json

node.js - 为什么 Mongoose 不更新?

javascript - Sails.js 通过 id 查找多个数据库条目

javascript - 如何使用 onClick 写入文本文件?

javascript - Vue.js - Highmaps - 从图表内部更改变量的值

javascript - $.ajax调用node js等效吗?

node.js - 运行nucleus-styleguide时出错

javascript - Google map 标记 - 为每个标记添加一个带有唯一标签的自定义图标

javascript - 使用纯 javascript 从具有相同类的所有 div 获取值