tags:

views:

694

answers:

8

Hello all,

Is there a way to get the function parameter names of a function dynamically?

Lets say my function looks like this:

function doSomething(param1, param2, .... paramN)
{
   // fill an array with the parameter name and value
   // some other code 
}

Now how would I get a list of the parameter names and their values into an array from inside the function?

Thanks,

+2  A: 

param values are easy, they are contained in an array called

arguments

you cant get their names as far as i know. why do you need that?

mkoryak
technically, `arguments` is Array-like, at least in some implementations. That's why you'll see code that copies values from it into a variable (typically called args) so that you can use all the array functions on it.
Hank Gay
I wrote an ajax application and if the request fails because something did not work on the server, then I need to know the parameters that were passed to the request.
vikasde
Firefox used to support named parameters in `arguments`. But that's not the case anymore. They've deprecated a lot of things about `arguments` and ECMAScript is trying to get rid of this object.
Ionuț G. Stan
+1  A: 

I don't know how to get a list of the parameters but you can do this to get how many it expects.

alert(doSomething.length);
Ólafur Waage
+4  A: 

I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.

//define like
function test(args) {
    for(var item in args) {
        alert(item);
        alert(args[item]);
    }
}

//then used like
test({
    name:"Joe",
    age:40,
    admin:bool
});
Hugoware
I have to many functions already pre-defined that are being called with standard parameters instead of a single object. Changing everything would take to much time.
vikasde
A: 

I think you need this procedure in order to easily refer your parameters thru functions. I suggest you to use JSON instead of Arrays as @HBoss said!

+1  A: 

I don't know if this solution suits your problem, but it lets you redefine whatever function you want, without having to change code that uses it. Existing calls will use positioned params, while the function implementation may use "named params" (a single hash param).

I thought that you will anyway modify existing function definitions so, why not having a factory function that makes just what you want:

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var withNamedParams = function(params, lambda) {
    return function() {
        var named = {};
        var max   = arguments.length;

        for (var i=0; i<max; i++) {
            named[params[i]] = arguments[i];
        }

        return lambda(named);
    };
};

var foo = withNamedParams(["a", "b", "c"], function(params) {
    for (var param in params) {
        alert(param + ": " + params[param]);
    }
});

foo(1, 2, 3);
</script>
</head>
<body>

</body>
</html>

Hope it helps.

Ionuț G. Stan
A: 

Thanks to everybody. After searching around, I found the solution on SO:

http://stackoverflow.com/questions/914968/inspect-the-names-values-of-arguments-in-the-definition-execution-of-a-javascript

It uses a regex to get the param name. Its probably not the best solution, however it works for me.

vikasde
A: 

You can access the argument values passed to a function using the "arguments" property.

    function doSomething()
    {
     var args = doSomething.arguments;
     var numArgs = args.length;
     for(var i = 0 ; i < numArgs ; i++)
     {
      console.log("arg " + (i+1) + " = " + args[i]); 
                    //console.log works with firefox + firebug
                    // you can use an alert to check in other browsers
     }
    }

    doSomething(1, '2', {A:2}, [1,2,3]);
letronje
Isn't arguments deprecated? See the suggestion of Ionut G. Stan above.
vikasde
vikasde is right. Accessing the `arguments` property of a function instance is deprecated. See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Functions/arguments
Ionuț G. Stan
A: 

Here's one way:

// Utility function to extract arg name-value pairs
function getArgs(args) {
    var argsObj = {};

    var argList = /\(([^)]*)/.exec(args.callee)[1];
    var argCnt = 0;
    var tokens;

    while (tokens = /\s*([^,]+)/g.exec(argList)) {
        argsObj[tokens[1]] = args[argCnt++];
    }

    return argsObj;
}

// Test subject
function add(number1, number2) {
    var args = getArgs(arguments);
    alert(args.toSource()); // ({number1:3,number2:4})
}

// Invoke test subject
add(3, 4);

Note: This only works on browsers that support arguments.callee.

Ates Goral