How do I forward the arguments from within a function to another function?
I have this:
function SomeThing(options) {
function callback(callback_name) {
if(options[callback_name]) {
// Desiring to call the callback with all arguments that this function
// received, except for the first argument.
options[callback_name].apply(this, arguments);
}
}
callback('cb_one', 99, 100);
}
What I get in the a
argument is 'cb_one', but I want that it should be '99'.
var a = new SomeThing({
cb_one: function(a,b,c) {
console.log(arguments); // => ["cb_one", 99, 100]
console.log(a); // => cb_one
console.log(b); // => 99
console.log(c); // => 100
}
});
How do I do this?
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
Higher Order FunctionsBecause functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
Argument Order MattersThe order or arguments supplied to a function matters. R has three ways that arguments supplied by you are matched to the formal arguments of the function definition: By complete name: i.e. you type main = "" and R matches main to the argument called main .
Use options[callback_name].apply(this, [].slice.call(arguments,1));
[].slice.call(arguments,1)
converts the arguments ('array-like') Object
into a real Array
containing all arguments but the first.
[].slice.call
may also be written as Array.prototype.slice.call
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With