0

Ok so let's say I have an assortment of varables:

tab = document.createOjbect('table');
str = 'asdf';
ary = [123, 456, 789];
obj = {a:123, b:456, c:789};

A Piece of code to 'stringify' them:

function Stringify(){
    var con = this.constructor.name;
    if(con == 'String')             return this;
    if(con == 'Arrray')             return this.toString();
    if(con == 'Object')             return JSON.stringify(this);
    if(con == 'HTMLTableElement')   return this.outerHTML;
}

An array containing the variables:

var aVar = [tab, str, ary, obj];

And I loop the array to 'stringify' its content:

for(var i in aVar){
    console.log(
        Stringify.call( aVar[i] );
    );
}

I get the expected list of stringed objects:

<table></table>
asdf
123,456,789
{"a":123,"b":456,"c":789}

But what if I wanted to include the name of the variables in the logs?:

tab: <table></table>
str: asdf
ary: 123,456,789
obj: {"a":123,"b":456,"c":789}

How would I even go about that?:

for(var i in aVar){
    var id = // get the name of the variable at aVar[i]
    console.log(
        id + ': ',
        Stringify.call( aVar[i] );
    );
}
LostInCyberSpace
  • 413
  • 4
  • 19
  • 2
    You can't, the only way that "might" work is looking at all defined variables for something with the same value, but this (as you can imagine) has a edge case where multiple variables with the same value are then indistinguishable) – Jason Sperske Feb 23 '15 at 21:03
  • 1
    This might shed some light on on the various approaches people have tried: http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript – Jason Sperske Feb 23 '15 at 21:05
  • 1
    Off topic, but this.constructor.name seems unusual, why not use typeof ? – Adam Feb 23 '15 at 21:05
  • 1
    It's not possible to do this reliably, so I wouldn't bother. You might be able to write a source code transform which somehow injects metadata, but is it worth it? – Felix Kling Feb 23 '15 at 21:06
  • @Adam because `typeof [0,1,2] === 'Object'`, although you might expect it to be 'Array' – blex Feb 23 '15 at 21:06
  • forgive me i'm fairly uneducated when it comes to coding, if i use typeof on an array,string etc the result is always `object`. – LostInCyberSpace Feb 23 '15 at 21:08
  • Just interested, thanks for explaining – Adam Feb 23 '15 at 21:09
  • You can use `aVar = Object.keys( window )` to get the list of defined and then filter if the values match – nanndoj Feb 23 '15 at 21:09
  • 1
    @nanndoj: You forgot to mention that this only works for global variables (which should be avoided anyway). – Felix Kling Feb 23 '15 at 21:12
  • @FelixKling Totally agree with you! – nanndoj Feb 23 '15 at 21:21
  • cheers guys, looks like it can't be done, bummer, someone phone JavaScript and tell them their fired! – LostInCyberSpace Feb 23 '15 at 21:32
  • 1
    Don't blame javascript. IMO they're totally right to not make this possible. If you want to give the things names which you can access, then the way to do it is probably to structure things a little differently. If you don't care what order they're in, try: `var allTheThings = { tab: document.createObject('table'), str: 'asdf', ary: [123, 456, 789], obj: {a:123, b:456, c:789} };`. Otherwise you could try `var allTheThings = [ ['tab', document.createOjbect('table')], ['str', 'asdf'], ['ary', [123, 456, 789]], ['obj', {a:123, b:456, c:789}] ];`. – David Knipe Feb 23 '15 at 21:59
  • @DavidKnipe: I understand this, this is how i would do it. But it's not how I wanted to do it... – LostInCyberSpace Feb 23 '15 at 22:14

1 Answers1

1

It is not possible, and does not really make sense. You have to understand that functions manipulate values, not variables.

When executing this:

var aVar = [tab, str, ary, obj];

What is put in the array is values, not variables, although it syntactically looks so. The values know nothing about the variables that reference them.

Think about it: a value could be referenced by several variables. What sense would it make to get the access the name of (one of the) variable that has referenced it at some earlier point?

I'm afraid that the only solutions for your use case are to either carry the 'variable name' along your execution flow, or to hardcode your logic for each of the variables.

Valentin Waeselynck
  • 5,950
  • 26
  • 43
  • ok so forget the array, it was a rash construct anyway, what if it was added to the prototype as a getter, then: `tab.Stringify` for the same result? surely `this` in the definition directly references the variable? – LostInCyberSpace Feb 23 '15 at 22:51
  • No. `this` references the *value* of the variable. It has no knowledge of the other variables which may reference it as well. Javascript's `var`s are not first-class citizen's; you can't programmatically pass them around nor access the name with which you wrote them. – Valentin Waeselynck Feb 24 '15 at 08:30
  • forgive me i'm self taught, and not very well taught either apparently... i kinda assumed a `var` was an independent object of sorts, rather than a mere reference, guess i need to do a bit more research before buggin u guyz – LostInCyberSpace Feb 25 '15 at 18:53
  • There is nothing to forgive :) bumping into such walls is a great way for you to learn, and an occasion for the more experienced ones to rethink what they take for granted. – Valentin Waeselynck Feb 25 '15 at 22:13