I am curious if it is possible to set the name of an object in Javascript to a variable value. So if I declare a variable objectName and want to create a new object whose name is the value of objectName.
- Could you maybe give an example of how you imagine it would work? The description is little vague.Viele– Viele2016-01-16 19:22:49 +00:00Commented Jan 16, 2016 at 19:22
- Look hereVolodymyr Chumak– Volodymyr Chumak2016-01-16 19:24:30 +00:00Commented Jan 16, 2016 at 19:24
- Thanks @Slam, thats perfect.SeanBallentine– SeanBallentine2016-01-16 19:28:31 +00:00Commented Jan 16, 2016 at 19:28
Add a comment |
1 Answer
Try this:
var objectName = "myObjectName"; window[objectName] = { foo: "bar" }; console.log(myObjectName); // { foo: 'bar'} All global variables are properties of the window object, and since window is an object, we can create a dynamic property using [] syntax. And then you can access it as window.myObjectName, window["myObjectName"] or just plain myObjectName
More info of window object here: http://www.w3schools.com/js/js_window.asp and here https://developer.mozilla.org/es/docs/Web/API/Window/window
1 Comment
Bergi
Don't use this. Don't create global variables.