0

say I have a function:

function foo(){
console.log(arguments);
}

process.nextTick(foo);

how can I apply arguments to foo in the process.nextTick() call?

how do I do something like

//pseudo code

var args = [];
process.nextTick(foo.addArgs(args));

...but without calling foo?

1
  • 1
    w/Array: Function.apply.bind( foo, null, ['arg1', 'arg2', 'arg3']) Commented May 18, 2015 at 21:21

2 Answers 2

3

There are a few possibilities. For the first several options, I'm (perhaps wrongly) assuming that you don't mind passing args as a single array parameter. If you want each element of args to be a separate argument to foo(), see the last example (using apply()).

Assuming you don't use this inside of foo(), here are some options:

process.nextTick(function () { 
  foo(args); 
});

Or:

var bar = foo.bind(null, args);
process.nextTick(bar);

If you use this inside of foo(), change null in the above example to the value that you expect this to have. For example:

var bar = foo.bind(foo, args);
process.nextTick(bar);

You may also wish to look at call() and apply(). apply() is especially useful if you want to have an array (say, [1, 2, 7]) that you want spread out across the function args (that is to say, foo(1, 2, 7) instead of foo([1, 2, 7])):

process.nextTick(function () {
    foo.apply(null, args);
}

As with bind(), if you use this inside of foo, then change null in the above example to be the value that you expect this to have.

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

1 Comment

this seems fairly legit
2

You can do that with an anonymous function:

var args = [];
process.nextTick(function(){
   foo.apply(foo, args);
});

1 Comment

this is the most straightforward solution, but I want to know other ways to do it as well

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.