Reputation: 151
spread(someFunction, [1, true, "Foo", "bar"] ) // is the same as...
someFunction(1, true, "Foo", "bar")
I wrote this code but got some errors:
function spread(func, args) {
func();
}
function func(args){
console.log(args[0] + args[1]);
}
spread(func,[5,6])
TypeError: args is undefined, but I can't define it because it will be defined when call the function.
spread(func,[5,6])
And i can't use variable either. I can just this kind of function. (This is a test)
Upvotes: 0
Views: 130
Reputation: 43718
There is only 2 ways to implement such function in JS. One which is generating a string that expresses the function call and evaluate it and the other using Function.prototype.apply.
spread(add, [1, 2]); //3
function add(num1, num2) { return num1 + num2; }
function spread(fn, args) {
return fn.apply(null, args);
}
Upvotes: 2
Reputation: 231
You must pass the arguments to func and also return it if you want to keep the result in a variable.
function spread(func, args) {
return func(args);
}
function func(args){
console.log(args[0] + args[1]);
//do something more, maybe:
return (args[0] + args[1])
}
var result = spread(func,[5,6])
Upvotes: 0