javascript - 使用 javascript/nodejs 创建动态方法

标签 javascript node.js method-invocation

我正在尝试创建一个具有这样的 api 的 Nodejs 模块

**program.js**

var module = require('module');
var products = module('car', 'pc'); // convert string arguments to methods

// now use them 
products.car.find('BMW', function(err, results){
  // results
})

products.pc.find('HP', function(err, results){
  // results
})

>

**module.js**

function module(methods){
  // convert string arguments into methods attach to this function
  // and return
}

module.find = function(query){
  // return results
};

module.exports = module;

我知道这是可能的,因为这个 module正在做完全相同的事情。 我试图研究源代码,但有太多进展,所以无法确定它是如何做到这一点的。

最佳答案

也许是这样的?如果没有额外的细节,有点难以回答:

function Collection(type) {
    this.type = type;
}

Collection.prototype = {
    constructor: Collection,
    find: function (item, callback) {
        //code to find
    }
};

function collectionFactory() {
    var collections = {},
        i = 0,
        len = arguments.length,
        type;

    for (; i < len; i++) {
        collections[type = arguments[i]] = new Collection(type);
    }

    return collections;

}

module.exports = collectionFactory;

关于javascript - 使用 javascript/nodejs 创建动态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595788/

相关文章:

mysql - 当推荐选择 promise 时,为什么 express 和 node 大量使用回调?

java - 方法调用是如何发生的?

javascript - 在 cordova 中从 objective-c 调用 javascript

javascript - 如何使用 ReactJS 从输入字段获取所有值?

javascript - 如何获取特定的同级值

javascript - Craigslist 如何确定您是否处于隐身模式

javascript - Chrome 内联插件安装在 window.confirm 上

javascript - 未捕获的类型错误 : b is not a function in nodejs(electron)

c# - 协助 UI Dispatcher 处理大量的方法调用

java - Eclipse JDT : How to find JDK MethodInvocation and ClassInstanceCreation