0

I've been batting this around my head for too long. Thanks to anyone who can help!

var foo = {key: 'value'};

Example 1:

var stringIntoReference = function(nameOfObject){
  console.log(someUnknownCode(nameOfObject));
};

stringIntoReference('foo');  // logs an object: {key: 'value'}

Example 2:

var referenceIntoString = function(nameOfObject){
  console.log(someUnknownCode(nameOfObject));
};

referenceIntoString(foo);  // logs a string: 'foo'
  • 1
    1. possible, 2 impossible – Jaromanda X Sep 08 '16 at 06:54
  • Related: [Why can't I get the variable name as a string? I want to create my own 'console.log' function](http://stackoverflow.com/q/39260444/218196) – Felix Kling Sep 08 '16 at 06:58
  • 1
    If the variable is in global scope you can try `this[nameOfObject]` but that's a terrible practice. It's better to just create 1 more object ( a namespace, basically) and store the `foo` inside it under the key `foo`. You can then access the objects by their names (key names). – Azamantes Sep 08 '16 at 07:02
  • Thanks for the reply, Asamantes. I'm trying to picture what that would look like. Do you mean create an object in the function? Can do, but I'm not sure how that would let me access the object 'foo' with only a string 'foo'. – Nathanael Ligon Sep 09 '16 at 15:58

1 Answers1

1

For the first, eval will do the trick. Be aware it's dangerous because it can run arbitrary code.

var foo = {key: 'value'};
var stringIntoReference = function(nameOfObject){
  console.log(eval(nameOfObject));
};
stringIntoReference('foo'); // {key: 'value'}

Note that eval will evaluate your reference in stringIntoReference, which may have a different scope than the place where you call it.

The second is not really possible. Identifier resolution happens before the call, the function only receives the resulting value. Well, you could use a dirty trick and hijack the scope via a proxy with statement, but doesn't seem exactly what you want.

var referenceIntoString = function(nameOfObject) {
  console.log(nameOfObject);
};
var p = new Proxy({}, {
  has: (_, prop) => prop !== "referenceIntoString",
  get: (_, prop) => prop,
});
with(p) {
  referenceIntoString(foo); // 'foo'
}
Oriol
  • 274,082
  • 63
  • 437
  • 513