I need to achieve following in my Node.js program.
Suggest me a better approach to achieve this or code snippet somewhere already implemented this.
var functions = ["foo", "bar", "baz"];
We iterate over the function list and call the __call
function.
functions.forEach(function(f){
__call(f);
});
This step is dependent on framework. If you're using node, you have to use the global
object. If you're using a browser (HTML) you have to use the window
object.
For the former, use:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
global[f].apply(null, args);
};
For the latter, use:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
window[f].apply(null, args);
};
The only difference is we're using the window
or global
dictionary to access the function.
EDIT: Added passing parameters.
You can do like this;
function foo(v){console.log("foo: ",v)}; function bar(v){console.log("bar: ",v)}; var funs = ["foo", "bar"], i = 0; while (i < funs.length) this[funs[i]](i++);
Well of course your functions definitions might reside in a particular scope and you may need to invoke them from within whatnot..! In that case you can of course wrap the above code in a function and bind it to whatever scope your function definitions are made in. Such as
var obj = { foo: function(v){console.log("foo: ",v)}, bar: function(v){console.log("bar: ",v)} }, funs = ["foo", "bar"], runner = function(a){ var i = 0; while (i < a.length) this[a[i]](i++); }.bind(obj); runner(funs);
You can call a function by its name like this:
const functions = ['index', 'push'...];
functions[0]() // write your parameters inside. this will call 'index'
If those function are not async, just write the callings one after another. If they are async, use a helper like async.waterfall or async.series.
see 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.