0

Okay, so I really would rather avoid using eval at all costs, so I'm trying to figure out an alternative to calling a global function using the window object method:

var time = new Date();
var varname = time.getDay();

var obj = {'eleID':'varname'};
for (var key in obj) {
    var vn = obj[key];
    eval(vn); //this works
    window[vn]; //this doesnt work
}
CJT3
  • 2,788
  • 7
  • 30
  • 45

1 Answers1

2

You've named the function object, now call it:

window[vn]();
dbanet
  • 685
  • 5
  • 18
  • Sorry, I made a mistake, the variable I'm trying to get is just a string and not a function, so `window[vn]();` doesn't work. – CJT3 Jun 21 '14 at 03:56
  • @CharlesJohnThompsonIII then `window[vn]` must work. – dbanet Jun 21 '14 at 04:01
  • @CharlesJohnThompsonIII dunno, some local JSFiddle issue: the current scope is not global. Assign the string to `window.varname` explicitly, or don't use `var`, it will set the variable globally. http://jsfiddle.net/faV5a/1/ – dbanet Jun 21 '14 at 04:06
  • @CharlesJohnThompsonIII check if the scope where you assign `varname` is the global one. – dbanet Jun 21 '14 at 04:07
  • that was just so I don’t have to use `window[obj[key]];` but that doesnt work either... – CJT3 Jun 21 '14 at 04:07
  • I don't understand what doesn't work. The fiddle I provided does work. – dbanet Jun 21 '14 at 04:08
  • Yeah, your update to it seemed to work... but even if I use the `winnow.` prefix when defining `varname` in my code it doesn't change. – CJT3 Jun 21 '14 at 04:13
  • I think I may just have to use eval. Nothing in that interacts with this code is user-defined, so it should be safe right? – CJT3 Jun 21 '14 at 04:14
  • @CharlesJohnThompsonIII post your code to JSFiddle so that I can look. – dbanet Jun 21 '14 at 04:14
  • uhh… ALL of my code? It’s a couple thousand lines, and will break in JSfiddle because it won’t have access to all of the resources it needs. :P – CJT3 Jun 21 '14 at 04:16
  • @CharlesJohnThompsonIII no, the only part that makes troubles. – dbanet Jun 21 '14 at 04:17
  • @CharlesJohnThompsonIII `obj[str]` operation returns the child object of `obj` with name `str`. If you have `obj.foo.bar`, you cannot address `bar` with `obj["foo.bar"]`, because it will try to return an object with name `"foo.bar"`, while you want to get an object with name `"foo"`, and then its child `"bar"`. – dbanet Jun 21 '14 at 04:35