Passing all parameters from one function to another? (JavaScript)
How to pass all parameters of one function to another
function a(){
arguments.length;// this is 1
// how do I pass any parameter function a receives into another function
b(what to put here?); // say pass all parameters function a receives to function b
}
a('asdf'); // this is okay
So, if function a takes X number of parameters, each parameter is then passed to function b in the same order. So if ("1", "2") ;, b ("1", "2"); if a ("1", 2, [3]) ;, b ("1", 2, [3]);
source to share
Use for example:Function.prototype.apply(thisArg[, argsArray])
b.apply(this, arguments);
Now arguments
is an array-like object that has some other properties (for example callee
) besides its n-index properties. So you should probably use to turn an object into a simple array of arguments (although either will work in modern environments).Array.prototype.slice()
b.apply(this, Array.prototype.slice.call(arguments));
See also: Function.prototype.call()
source to share
why not pass them as a single object? the advantages of using a single object as a parameter are that
- no order required. as opposed to arguments where you have to know if they are first, second, third in the receiving collection, in an object, they are just there. name them when you need them.
- you never worry about how much has been passed. you can send one object containing many properties - and you only pass one argument between the caller and the callee
of course you should check them if they exist before using
function foo(data){
data.param1; //is foo
data.param2; //is bar
data.param3; //is baz
//send params to bar
bar(data);
}
function bar(info){
info.param1; //is foo
info.param2; //is bar
info.param3; //is baz
}
//call function foo and pass object with parameters
foo({
param1 : 'foo',
param2 : 'bar',
param3 : 'baz'
})
source to share