Reputation: 21810
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
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);
};
this
is preserved.NOTE: This method works in most cases. Though there are edge cases where this method will fail, including:
Object.defineProperty
with writable:false
)Upvotes: 35
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
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
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