Kristian
Kristian

Reputation: 21810

How to get all arguments of a callback function

Very often, I find myself using a callback function and I don't have its documentation handy, and it would be nice to see all of the arguments that are meant to be passed to that callback function.

// callback is a function that I don't know the args for...
// and lets say it was defined to be used like: callback(name, number, value)
something.doSomething( callback );

How can I determine what args its passing into that?

Note: looking at the source code can be unhelpful when the code itself is obfuscated and minified (as many js frameworks are)

Upvotes: 23

Views: 29856

Answers (4)

Rob W
Rob W

Reputation: 348992

To get the list of arguments without breaking functionality, overwrite the callback function in this way:

var original = callback;
callback = function() {
    // Do something with arguments:
    console.log(arguments);
    return original.apply(this, arguments);
};
  1. The context, this is preserved.
  2. All arguments are correctly passed.
  3. The return value is correctly passed.

NOTE: This method works in most cases. Though there are edge cases where this method will fail, including:

  • Read-only properties (e.g. defined using Object.defineProperty with writable:false)
  • Properties that are defined using getters/setters, when the getter/setter is not symmetric.
  • Host objects and plugin APIs: E.g. Flash and ActiveX.

Upvotes: 35

Cody
Cody

Reputation: 10015

You can even tell it which function's args to get using [functionName].arguments:

(function(arg1, arg2, agr3){
    console.log('args are:', arguments);
    return function fn(){
        function m(){
            console.log(
                'fn.arguments:', fn.arguments,
                'm.arguments:', m.arguments,
                'argumentsX:', arguments
            );
        };
        m('mArg1', 'mArg2', 'mArg3', 'mArg4');
    };
})
(1, 2, Math.PI)  // invoke closure
('fnArg1', 'fnArg2', 'fnArg3', 'fnArg4');  // invoke "fn"

Every function def rewrites the the arguments keyword to be of that scope btw (as seen with the "argumentsX" log).

Upvotes: 0

user1207456
user1207456

Reputation:

Isn't this sort of the cart leading the horse?

Your function takes a callback. It's the method using your function that should be aware of what arguments the callback should accept.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338178

Could it be as easy as

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

?

Every function provides the arguments it has been called with in the automagic arguments collection.

Upvotes: 8

Related Questions