Create object from string

If you know the context, yes. Let’s say you’re in a browser environment and Person is a global constructor. Because any global variable is a property of the global object, it means you can access to Person through the global object window:

var p = new Person()

Is equivalent to:

var p = new window.Person()

So you can use the square bracket notation:

var p = new window["Person"]();

Of course this is valid for every kind of object. If you don’t want pollute the global scope, you can have:

var mynamespace = {};

mynamespace.Person = function Person() {..}

var p = new mynamespace["Person"]();

Leave a Comment