Reputation: 6554
function validateArguments(args)
{
if(args.length < 1 && args.length > 2)
{
throw new RangeError("Invalid amount of arguments. Follow the syntax");
}
if(typeof args[0] !== "object")
{
throw new TypeError("Invalid first argument type. Follow the syntax");
}
if(args[1] && typeof args[1] !== "function")
{
throw new TypeError("Invalid second argument type. Follow the syntax");
}
return true;
}
What I'm trying figure out is for args[1]
if it is a function get the arguments list of that as well. Is this possible? Basically, here is an example code.
someFunction({ object:"//object" },function(data,datas,dataCall){
//is data, datas, and dataCall too many arugments.
//if so how to throw the error here
});
Upvotes: 0
Views: 51
Reputation: 816462
What I'm trying figure out is for
args[1]
if it is a function get the arguments list of that as well. Is this possible?
Kind of, but it's not 100% reliable. You can access the length
property of the function, which returns it's arity. For example:
function foo(a, b, c) {
}
foo.length;
// 3
If you want to get the names of the parameters, you could convert the function to a string and extract the list of parameters, just like in this answer.
However, since functions can access its arguments even without formally defined parameters (via arguments
), this is not a reliable technique. But there isn't any either way.
Upvotes: 1
Reputation: 634
Your args
is just the first argument. There is a special arguments variable that captures all the given arguments passed to the function. You can use it like this:
function myFunction () {
if (arguments.length < 1 || arguments.length > 2)
throw new RangeError("Invalid amount of arguments. Follow the syntax")
if (typeof arguments[0] !== "object")
throw new TypeError("Invalid first argument type. Follow the syntax")
if (typeof arguments[1] !== "function")
throw new TypeError("Invalid second argument type. Follow the syntax")
// do stuff
}
I'm not sure on what you are asking though. If you want to use your validateArguments
function from inside other functions to check their arguments, you can do so by passing their arguments
object/array (array-like, really) to the checker:
function someFunction () {
validateArguments(arguments)
// do stuff
}
I didn't understand what you meant by the bit with the callback at the end. If you want to restrictions on the arguments a callback function will be able to have you are out of luck. You can not impose restrictions on function declarations (if you are not writing them yourself), but you control what you pass to them, so...
Upvotes: 1
Reputation: 3165
You can do this.
someFunction: function() {
if(validateArguments(arguments)) {
var object = arguments.shift();
var func = arguments.shift();
func.apply(this,arguments);
// Do whatever you want
}
},
You can use arguments, which will have all the argument list.
Upvotes: 0