Dynamic object initialization In JavaScript (how does PHP Reflection do it)?

Using Reflection in PHP I can dynamically create an object like this

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

      

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

+2


a source to share


3 answers


Your comment states:

So, I can create "view controller" objects based on the requested view. I do not know until what time the request is being executed.

I suggest storing all views in an object views

like this:



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

      

Then, using parenthesis notation, you can access any constructor of the kind:

var viewName = 'Foo';
var instanceOfView = new views[viewName];

      

+6


a source


SomeClass = function(arg1, arg2) {
    // ...
}

ReflectUtil.newInstance('SomeClass', 5, 7);

      

and implementation:



/**
 * @param strClass:
 *          class name
 * @param optionals:
 *          constructor arguments
 */
ReflectUtil.newInstance = function(strClass) {
    var args = Array.prototype.slice.call(arguments, 1);
    var clsClass = eval(strClass);
    function F() {
        return clsClass.apply(this, args);
    }
    F.prototype = clsClass.prototype;
    return new F();
};

      

+1


a source


I don't think there is such a thing as the Reflection API in JavaScript. But JavaScript doesn't have classes anyway. Prototypes / functions are (first-class) objects, just like everything else. It can be annoying, but it can also be very helpful.

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

      

Haven't tested this.

-1


a source







All Articles