I'm trying to dynamically create node.js variables that point to objects.
I know I can create a variable dynamically in scope using eval:
var vars = ['a','b']
for(var n=0; n<vars.length; n++) {
eval('var '+vars[n]+' = '+n)
}
console.log(b) // prints 1
The above dynamically creates variables and gives them a value of whatever their index is inside the vars list.
But what if I want to set these dynamic variables to an object reference? Something like the following:
var vars = {a: {}, b:{}}
for(var k in vars) {
eval('var '+k) // create the variable dynamically
new Function('value', k+' = value')(vars[k]) // attempt to set the value
}
a.b = 5
console.log(vars.a.b) // undefined : (
I know why the above doesn't work - the function created by new Function can't see the current scope, and so can't set the value. Is there a way to do what I'm trying to do, such that console.log(vars.a.b) would print "5" rather than "undefined"?
UPDATE:
Hmm, I was wrong that new Function can't see or modify variables in the local scope, since this works:
var obj = {}
eval('var x')
new Function('value', 'x = value')(obj)
obj.a = 5
console.log(x.a) // prints 5
So now I'm pretty confused why my loop above doesn't seem to work..
UPDATE 2:
I just realized that my code actually does work in chrome's console. But its not working in node.js...
UPDATE JUST FOR PHIL:
Here's my situation. I'm using Parsimmon to build a parser combinator. This is how that's done:
var L = Parsimmon.createLanguage({
combinator1: function() {
return Parsimmon.string('hi')
},
combinator2: function() {
return L.combinator1.many()
}
})
I'd like to eliminate the need to write L. before every parser combinator I write. I could do this:
var combinator2 = L.combinator2
But that would require me to add an additional line like that for every combinator I write. As you can see, I can't use with since L is created after I'd be able to write with(L) and if I define my functions below then use them in the object, I'm back to duplicating those function names every time i write a new combinator.
So to summarize, I'd like to loop through L and put all the generated parser combinators into a nice clean variable in scope so I can write combinator1 instead of L.combinator1 (etc).
(var[k])looks suspicious. Should be(vars[k])? Nothing to do with answering your question though.varkeyword inside your function?with, egwith(objectPrefix) { console.log(prop) }. Can't be any worse thaneval