Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'forward' all-but-the-first-argument arguments of a function to another function?

Tags:

javascript

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?

like image 200
Zabba Avatar asked Jul 07 '13 07:07

Zabba


People also ask

How do you pass an argument from one function to another in JavaScript?

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.

How do you pass an argument to another function in Python?

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.

Does the order of arguments in a function matter?

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 .


1 Answers

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.

like image 105
KooiInc Avatar answered Oct 08 '22 17:10

KooiInc