0

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?

1
  • Where is this function? You have to have a way of finding the thing you want to push first. Would you rather make sure you pass the right function instead of finding the function in this step? Commented Nov 7, 2014 at 20:51

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Use bracket notation if it is in global scope

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

Comments

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.