I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
Share Improve this question edited Nov 20, 2012 at 23:10 Linus Kleen 34.7k10 gold badges97 silver badges100 bronze badges asked Nov 20, 2012 at 23:09 KatKat 6662 gold badges11 silver badges24 bronze badges 4- 4 It is not possible for a function to know the name of the variable passed by its caller. – SLaks Commented Nov 20, 2012 at 23:12
- @SLaks: ... as long as you don't parse a stacktrace with stringified functions :-) – Bergi Commented Nov 20, 2012 at 23:19
- 1 @SLaks There's an horrible way to do it. See my answer – lukedays Commented Nov 20, 2012 at 23:48
- @lukedays: Key word being horrible. – SLaks Commented Nov 21, 2012 at 4:12
5 Answers
Reset to default 1Assuming rabbit
is supposed to be a string:
func("rabbit");
If rabbit
is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.
Actually there's an ancient way to retrieve the variable name.
var func = function(variable)
{
console.log(variable); // outputs "white"
console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}
rabbit = 'white';
func(rabbit);
See it running http://jsfiddle/Q55Rb/
You could do this
function whatever(input) {
return '\"' + input + '\"';
}
result should be in quotes
I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:
var func = function(variable) {
window[variable] = 'abc'; // Setting the variable as what is passed in
window.result = variable; // Normal
}
func('rabbit'); // Will set both window.rabbit to 'abc', and window.result to 'rabbit'
I wouldn't advise setting global variables, though. More info
Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.
I have this in my function:
defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}};
Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?