Jump to content

Creating objects dynamically


Recommended Posts



Probably a really basic answer here but I'm stuck and google isn't bringing me any closer.



Is it possible to dynamically create objects using a variable?


For instance in PHP I might do:

class turnip {
	public function __construct(){
		echo 'created turnip';

$t = 'turnip';
$tt = new $t(); //echoes created turnip

However, trying to do something similar in JS is simply causing an error.  So is there a special trick?


Lets say I wanted to do:

function Pawn(){...}

var p = 'Pawn';

var a = new p(); //Can this be done somehow? Can you force the variable 'p' to evaluate down to it's value?
Link to comment
Share on other sites

You're defining a function in the scope of window. What happens is the function becomes a property of the window object. If you inspect "window", you'll see that your function "Pawn" is actually a property. You could say window.Pawn() and it would execute your function.

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.