Drongo_III Posted July 25, 2015 Share Posted July 25, 2015 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? Quote Link to comment https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/ Share on other sites More sharing options...
Drongo_III Posted July 25, 2015 Author Share Posted July 25, 2015 Found the answer. If this of any help to anyone you can call it by using the window object: var a = new window[p](); Quote Link to comment https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/#findComment-1517380 Share on other sites More sharing options...
Drongo_III Posted July 25, 2015 Author Share Posted July 25, 2015 Out of interest though can anyone explain why the window object works like that? How is the value of the variable gets used in that context? Quote Link to comment https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/#findComment-1517381 Share on other sites More sharing options...
scootstah Posted July 25, 2015 Share Posted July 25, 2015 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. Quote Link to comment https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/#findComment-1517386 Share on other sites More sharing options...
Drongo_III Posted July 25, 2015 Author Share Posted July 25, 2015 I think I see what you mean. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/297474-creating-objects-dynamically/#findComment-1517389 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.