Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  29] [ 7]  / answers: 1 / hits: 15362  / 12 Years ago, mon, april 23, 2012, 12:00:00

I want to create a log function where I can insert variable names like this:



var a = '123',
b = 'abc';

log([a, b]);


And the result should look like this in the console.log



a: 123
b: abc


Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.


More From » javascript

 Answers
27

so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:



[123,abc];


and nothing more






you could provide the function the names of the variables and the scope they are in, like:



function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}


however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:




  • for nonstrict functions, this is window

  • for strict functions, this is undefined

  • for constructor functions, this is the constructed object

  • within an object literal, this is the immediate enclosing object



so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.






if you pass them as an object, then you can iterate through the object and its keys and not the original variable names. however, this is more damage than cure in this case.


[#86056] Saturday, April 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;