javascript accessing the name of the parameters for debugging purposes
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 us开发者_运维知识库ed more than once!)
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'});
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/
try this :
function show_me() {
for (var i=0; i < arguments.length; i++) {
alert(arguments[i]);
}
}
show_me('a', 'b');
精彩评论