views:

83

answers:

3

Hi All,

Using Reflection in PHP I can dynamically create a object like so

$target = 'core_domain_Person';
$reflect = new ReflectionClass($target);
$obj = $reflect->newInstance();

I would like to replicate this same concept in JavaScript is there a way to do this out of the box? Or is there a way to replicate what Reflection is doing?

A: 

javascript has function eval. Read more on it here

http://www.w3schools.com/jsref/jsref_eval.asp

Universal
@Sarfraz: You asked a different question. He precisely answered your question albeit not very comprehensively.> Dynamic Object Initialization In JavaScript> Or is there a way to replicate what Reflection is doing?
codethief
@Universal thanks, should allow me to do what I want. @Sarfraz I don't need to replicate the entire functionality of the Reflection API (yet) just need to create a class in the same way as it. Like the eval function should allow me to do :)
Gcoop
A: 

I don't think that there is such a thing like a Reflection API in JavaScript. But in JavaScript there are no classes, anyway. Prototypes / functions are (first-class) objects like anything else. Might be annoying, but might also be very useful.

function create_instance(prototypeName) {
    eval('return new ' + prototypeName + '()');

Didn't test this, though.

codethief
+3  A: 

Your comment states:

So I can create "view controller" objects based on the requested view. I don't know until runtime what the view is that is being requested.

I suggest keeping all views in a views object like so:

var views = {
    Foo: function() {},
    Bar: function() {},
    Dah: function() {}
};

Then, using bracket notation, you can access any view constructor:

var viewName = 'Foo';
var instanceOfView = new views[viewName];
J-P
Thanks, I am going to do this! Should equal better performance I presume because I am not using eval().
Gcoop
Had to award @Universal the correct answer, because it was the first answer and the correct one for the question although your answer is a better solution :)
Gcoop