Reputation: 1
I am trying to create dynamic variables using Window. The exact thing I want to do is working fine with eval. But as you may know, that’s not advised.
Some examples.
I may define some variables like this.
var word1 = The;
var word2 = Number;
var word3 = Is;
var number = 100;
Now I combine them.
var phrase = word1+word2+word3+number.
If I use the window keyword in front of the phrase variable, then it will work, provided it is at the beginning of the line of code. However, if I try to put window in front of a variable in the middle of a line of code, it doesn’t work. However, eval does work. Example below.
window[phrase]
That will work.
But if it’s something like this
window[newCombinedVariable] = document.querySelector(window[newCombinedVariable2])
That will not work.
However, this will work.
window[newCombinedVariable] = document.querySelector(eval(newCombinedVariable2))
So, window can take a combination of strings with dynamic variables and it works at the beginning, but not in the middle, such as after doc/query selector. But eval works fine that way when using the exact same combined variables.
Can someone suggest what I must do in order for window to give me the same results as eval?
Upvotes: 0
Views: 73