Makerimages
Makerimages

Reputation: 384

Javascript create new object from class name in string

I've got this little bit of non working code:

PackageLoader.prototype.activate = function(name) {
    this.activePackages.push(new name());
}

What I'd like this to do is to push a new instance to the activePackages array, if the name it gets is a string. How to achieve this?

Upvotes: 0

Views: 2114

Answers (2)

Greg Burghardt
Greg Burghardt

Reputation: 18868

If name does not refer to a "class" in the global scope, you can safely use eval:

function toConstructor(className) {
    if (!/^[$_a-z][$_a-z0-9.]*$/i.test(className)) {
        throw new Error("Invalid class name: " + className);
    }

    try {
        return eval(className);
    }
    catch (error) {
        return null;
    }
}

And to use it:

var Foo = {
    Bar: {
        Baz: function() {}
    }
};

var Klass1 = toConstructor("XMLHttpRequest");

var xhr = new Klass1();
xhr.onreadystatechange = function() {};

var Klass2 = toConstructor("Foo.Bar.Baz");
var baz = new Klass2(3);
console.log(baz.x); // logs 3

var Klass3 = toConstructor("I.Do.Not.Exist");

console.log(Klass3); // logs NULL

Upvotes: 2

epascarello
epascarello

Reputation: 207527

Use bracket notation if it is in global scope

this.activePackages.push(new window[name]());

Upvotes: 0

Related Questions