简体   繁体   中英

Can I detect unused extra parameters passed to javascript methods?

In Javascript I can call any method with more than the necessary amount of parameters and the extra parameters are silently ignored.

eg

letters = ['a','b','c']
//correct
letters.indexOf('a')
//This also works without error or warning
letters.indexOf('a', "blah", "ignore me", 38)

Are there ways to detect cases where this occurs?

My motivation is that in my experience cases where this occurs are usually bugs. Identification of these by code analysis or at runtime would help track these errors down.

These cases are especially prevalent where people are expecting alterations to base types which may not have occurred. Logging a warning where this happens

eg

Date.parse('02--12--2012', 'dd--MM--YYYY')

Notes: To be clear I would like a solution that doesn't involve me sprinkling checks all over my code and other peoples' code.

You can use the arguments object.

function myFunction(param1,param2)
{
   if (arguments.length!=2)
   {
       // wrong param number!
   }
   ...
}

As per your edit: If you want to implement an automated form of check, without ever touching the original functions :

You still have to process each function with:

functionName = debug(functionName, numberOfExpectedArgs);

This operation wraps the function with a check of the number of arguments.

So we leave a sample function untouched :

// this is the original function... we want to implement argument number
// checking without insertint ANY debug code and ANY modification

function myFunction(a,b,c)
{
    return a + " " + b + " " + c;
}

// the only addition is to do this...
myFunction = debug(myFunction,3); // <- implement arg number check on myFunction for 3 args

// let's test it...    
console.log(myFunction(1,2,3));
console.log(myFunction(1,2));

You need to implement this debug() function:

function debug(f, n)
{
    var f2 = f;
    var fn = function()
        {
            if (arguments.length!=n) console.log("WARNING, wrong argument number");
            return f2.apply(f2, arguments);
        };
    return fn;
}

​

This solution is TOTALLY transparent as per already defined functions, so it may be what you seek for. I strongly suggest to check against deprecations (there are some) and crossbrowser compatibility.

The functions in JavaScript are objects. As such they have properties. What you want can be achieved with length MDN property, which specifies the number of arguments expected by the function .

function say ( hello, world ) {
    alert ( 
      "arguments length = " + arguments.length + "\n" +
      "defined with = " + say.length
    );
}
say ( "this ", "brave ", "new ", "world" );​

This works even on IE8. Demo . In your case you can do something like this .

Javascript is a very dynamic language and many of its useful features also make it impossible to do some checks statically.

The existance of the arguments implicit object means there is no way to automatically determine how many arguments a function is expecting for all functions. Many var-arg functions declare no formal arguments and uses the arguments object exclusively.

All you can reliably do is to check it manually in each function like Cranio suggested.

If you want to have automated checks, eg as part of your unit tests, you can make use of the length property of the Function objects, which returns the number of formal arguments. For var-arg functions, just don't include the check. For example:

function checkNumberOfArguments(args) {
    if (args.length != args.callee.length) {
        throw new Error('Wrong number of arguments');
    }
};

// Use it like

function a(b) {
    checkNumberOfArguments(arguments);
}

a(1);
a(1,2);

Inside function you can use arguments object, it contains an array of all the arguments that were supplied to the function when it was called.

function x(){
  return arguments.length;
}

x()
=> 0
x(1,1,1,1,1,1,1,1,1)
=> 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM