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 thi开发者_如何转开发s 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?
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];
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();
};
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.
精彩评论