我正在尝试创建一个具有这样的 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/