1

I want to do something like this:

function delegate(func, params) {
  func(params);
}

function foo(a, b) {
  // do stuff
}

function bar(x, y, z) {
  // do stuff
}

delegate(foo, 1, 2);
delegate(bar, 1, 2, 3);

I know delegate() will not do what I want as written. How can I write a delegate() that would work for the above examples?

2
  • 1
    Look for documentation on arguments. Commented Jul 9, 2015 at 18:51
  • MDN arguments. Commented Jul 9, 2015 at 18:54

3 Answers 3

3

Pass all the arguments with .apply and arguments:

function delegate(func) {
    var args = [].slice.call(arguments, 1);
    return func.apply(this, args);
}

Demo: http://jsfiddle.net/DerekL/8xkhrtg7/

Sign up to request clarification or add additional context in comments.

Comments

2

I'll throw my hat into the ring with an ES6 flavored example. I'm also using bind as opposed to call or apply in order to delay the function invocation.

function delegate(fn, ...args) {
  if (args.length !== fn.length) {
    console.log(`Warning, function ${fn.name} takes ${fn.length} arguments.`);
    return;
  }
  return fn.bind(null, args);
}

function foo(a, b) {
    console.log('foo invoked');
}

function bar(a, b, c) {
    console.log('bar invoked');
}

var whoops = delegate(foo, 1, 2, 3); // => 'Warning, function foo takes 2 arguments.'

var myFn1 = delegate(foo, 1, 2);
var myFn2 = delegate(bar, 1, 2, 3);

myFn1(); // => 'foo invoked'
myFn2(); // => 'bar invoked'

2 Comments

I knew somebody is going to make a ES6 answer for this question!
Haha, [].slice.call(arguments, 1); just asks for it. ...args just looks so much better!
1

In case you're still having trouble you can create the function like this:

function delegate(func) {
  var args = Array.prototype.slice.call(arguments, 1); 

  return func.apply(null, args); 
}

That should do what you're looking for.

// Examples 
function sum(x, y) {
  return x + y; 
} 

function sumThree(x, y, z) {
  return x + y + z;
}

delegate(sum, 4, 5); 
//=> 9 
delegate(sumThree, 1, 2, 3); 
//=> 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.