1

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.

3
  • Could you maybe give an example of how you imagine it would work? The description is little vague. Commented Jan 16, 2016 at 19:22
  • Look here Commented Jan 16, 2016 at 19:24
  • Thanks @Slam, thats perfect. Commented Jan 16, 2016 at 19:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Don't use this. Don't create global variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.