最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

callback - javascript send arguments object as argument - Stack Overflow

programmeradmin1浏览0评论

I need to pass arguments onto a callback function as real arguments. How do I do that? callback requires a variable number of arguments.

Example function like this:

var func = function (callback) {
  doSomething(function () {
    // the goal is to pass on the arguments object to the callback function as real arguments
    callback(arguments)
  });
}

Thanks in advance.

It might be a similar question to this: Is it possible to send a variable number of arguments to a JavaScript function?

But I didn't understand that question nor the answers.

Edit: If possible, I would like to not pollute global.

I need to pass arguments onto a callback function as real arguments. How do I do that? callback requires a variable number of arguments.

Example function like this:

var func = function (callback) {
  doSomething(function () {
    // the goal is to pass on the arguments object to the callback function as real arguments
    callback(arguments)
  });
}

Thanks in advance.

It might be a similar question to this: Is it possible to send a variable number of arguments to a JavaScript function?

But I didn't understand that question nor the answers.

Edit: If possible, I would like to not pollute global.

Share Improve this question edited May 23, 2017 at 12:08 CommunityBot 11 silver badge asked Mar 28, 2011 at 9:12 HarryHarry 55k76 gold badges185 silver badges270 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

Use apply to invoke the callback so the array items gets passed as individual arguments to the function.

callback.apply(this, arguments);

apply takes the context, and an array as an argument, and each item of the array can be passed as a named argument of the function being invoked.

function two(first, second) {
    alert(first), alert(second);
}

two.apply(null, ["Hello", "World"]); // alerts "Hello", then "World"

Implementations of ES3 required that the second argument to apply be either an array, or an arguments object. ES5 makes it more liberal in that as long as it resembles an array - has a length property, and corresponding integer indexes, it will work.

发布评论

评论列表(0)

  1. 暂无评论