4

Is there a way to make a variable classname in javascript. In php the next is allowed:

$classname = "klasse";
$class = new $classname();

Tom

3 Answers 3

8

Use square bracket notation:

some_object["string_containing_method_name"]();

If you want to play with globals, then just remember they are all properties of the window object.

… but don't play with globals.

Your particular example:

var $classname = "klasse";
var $class = new window[$classname]();

(Obviously, the usual conventions for only using $ in machine generated code should apply too)

Sign up to request clarification or add additional context in comments.

Comments

0

Bear in mind that "eval is evil", but if you are aware of this, then:

var classname= "klasse";
eval( "var obj = new " + classname + "();");

1 Comment

@David (author of a deleted comment that stated that eval shouldn't be used), that's why I added the disclaimer. However, the question sounds more theoretical than soon to be put to practical use.
0

If you want to call something like

new acme.tools.Hammer();

Then do

var $toolName = "Hammer";
var myObject = new window['acme']['tools'][$toolName]();

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.