1

I have a pretty straight forward question, however I can't seem to find a solution for it anywhere...

Basically I would like to instantiate a new Javascript object, but the class name is a variable. In PHP the implementation is fairly straight forward new $className(). I have tried the following solution in Javascript, without luck:

window.onload=function(){
function obj(){
    this.show = function(){
        console.log('Hallo World');
    }
}

var objs = ['obj'];

new objs[0]().show();
} 

Does anyone know how to pull this off?

1

2 Answers 2

3

With the code as shown, you can't do it without eval.

If you're willing to change it, you can:

window.onload=function(){
    var things = {
        obj: function(){
            this.show = function(){
                console.log('Hallo World');
            };
        }
    };

    new things['obj']().show();
    // Or: new things.obj().show();
};
Sign up to request clarification or add additional context in comments.

1 Comment

didn't see your answer and posted the same thing...this is correct anyway.
1

Will this help you:

var creator = {
    obj : function (){
        this.show = function(){
        console.log('Hallo World');
        };
    }
}
var myInstance = new creator['obj'];
myInstance.show();

The idea is to define the constructor as a property.

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.