0

Say you have

window.something = 123; 
var code = 'window.something'
var str = `${code}`

console.log(str)

Naturally that will output window.someting

Is there a way to declare an interpolated String and get the string to be evaluated?

Something like new InterpolatedString('window.something') and actually get whatever is in there? For the current context?

I know this might be much to ask for, but since the language is interpreted, they could have exposed this but I don't believe they have :/

mjs
  • 21,431
  • 31
  • 118
  • 200
  • 1
    *"...but since the language is interpreted..."* It *can* be. It isn't necessarily. – T.J. Crowder Oct 25 '20 at 11:32
  • 1
    1. This sounds like `eval` 2. Don't use `eval`. – VLAZ Oct 25 '20 at 11:32
  • 1
    Also relevant: [“Variable” variables in Javascript?](https://stackoverflow.com/q/5187530) – VLAZ Oct 25 '20 at 11:33
  • 1
    In the scenario you've shown, yes, you can do it without `eval` because `window` is a property name on the global object; see the linked question's answers for how. If you wanted to do this where the first segment was an arbitrary in-scope variable that wasn't a property on an object you could access, then no, you can't do it without `eval` or its cousin `new Function`. – T.J. Crowder Oct 25 '20 at 11:34
  • @T.J.Crowder it would have been terrificly convienient for use in a template engine. I am not sure how they execute code. Like underscore, and others. Eval is slow. Personally, I interpret the code within but that is with limits on what can be done. Maybe there is a javascript code by string executioner that can parse, you know? – mjs Oct 25 '20 at 18:52
  • What part of that answer did you want me to look at? For this example yes, it is simple. I can parse that. In theory an interpolated string can actually have arbitrary code to my experience thus far. I am not sure of the performance of it, but surely it has to be more performant than eval. I am not sure how they differ in implementation but they seem awefully similar. – mjs Oct 25 '20 at 18:56

0 Answers0