Jump to content

Creating objects dynamically


Drongo_III

Recommended Posts

Hello

 

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
https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.