2

is there anyway to access the "name" of the parameter as such:

function(arg1, arg2) {
    debug("arg1 is rotten!");
}

Right now if i change the parameter name I'd have to change the name within the string as well, so I was looking if javascript had a solution like How do i bind function arguments to the parameters i supply in creating an ArgumentException object?

I want a way to be able to do something like:

function(arg1, arg2) {
        debug(arguments[0].name+" is rotten!");
    }

so that I would not have to search for the changes and change accordingly whenever i change the name of the parameter (sometimes its used more than once!)

Community
  • 1
  • 1
Pacerier
  • 86,231
  • 106
  • 366
  • 634

3 Answers3

3

You cannot access variable names, only their values. The closest you can get is if your argument to your method is an 'options' style object (which is just a regular JavaScript object, but calling it 'options' or 'opts' and having that contain all your arguments is a very common practice):

function test(opts){
    for(var name in opts){
        console.log(name + ' with value ' + opts[name] + ' is rotten!')
    }
}

test({arg1: 'argument 1', arg2: 'argument 2'});
Matt
  • 41,216
  • 30
  • 109
  • 147
1

Whenever you have a function, there is an array in the function called arguments that holds all the arguments in it

see fiddle: http://jsfiddle.net/maniator/P5FvN/

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

try this :

function show_me() {
    for (var i=0; i < arguments.length; i++) {
        alert(arguments[i]);
    }
}

show_me('a', 'b');
Shanison
  • 2,295
  • 19
  • 26
  • you may want to read this http://stackoverflow.com/questions/1009911/javascript-get-argument-value-and-name-of-passed-variable – Shanison May 20 '11 at 15:40