0

I tried searching for this but really couldn't find just a super simple answer for this.

I want to be able to create an object with a name that is given by a parameter.

I.e. something like this:

var createThing = function (param) {
    var param = new Object();
}

I don't want an object called param rather an object with that is named after the string that is passed in as the parameter. I.e. if someone calls:

createThing(inventoryA);

I want to be able to have an object created called inventoryA

1 Answer 1

1

you can try :

var createThing = function (param) {
    return window[param] = new Object();
}
createThing('inventoryA');
console.log(inventoryA);

this will create a object in the window scope with the name you given.

with nodejs you can use:

var createThing = function (param) {
    return global[param] = new Object();
}
Sign up to request clarification or add additional context in comments.

3 Comments

would there be a way to do this in node.js as opposed to running in the browser?
It should be noted that doing this is a bad idea especially because it can introduce hard to debug issues...
@mscdex , what would be the best practice alternative to this? And what would be a good example of a hard to debug issue.

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.