1

I just read " Define global variable in a JavaScript function " and I wanted to try to do the same, but this time passing a string as the global variable name.

function createGlobal(strname){
    window.strname={
        name:"John",
        age:27
    };
}

createGlobal("myglobal");

//can't use "alert(myglobal.name);", myglobal is not defined and crashes
//however, this works v
alert(strname.name); //John

I am really new to objects, I also tried weird things like window.[strname], window.[""+strname+""] and window.["'"+strname+"'"] without results.

How can I create a global var by passing its name as string?

Community
  • 1
  • 1
ajax333221
  • 11,436
  • 16
  • 61
  • 95

1 Answers1

4

Try this inside createGlobal:

window[strname] = {name:"John", age:27};
faffaffaff
  • 3,429
  • 16
  • 27