Reputation: 12674
Is there a way to call a function (or a property) on an object via reflection, in JavaScript?
Lets say that during run-time, my code has already determined that objectFoo indeed has a property called 'bar'. Now that my code knows that, the next thing I want to do is invoke that. Normally i would do this: var x = objectFoo.bar. But 'bar' was determined at run time, so I need to invoke it using reflection.
Upvotes: 3
Views: 17266
Reputation: 20966
Create object (invoke constructor) via reflection:
SomeClass = function(arg1, arg2) {
console.log('Your reflection');
}
ReflectUtil.newInstance('SomeClass', 5, 7);
and implementation:
var ReflectUtil = {};
/**
* @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();
};
Upvotes: 4
Reputation: 859
Create a register object:
var funcRegister = {};
Create a function to call the other:
var callReflectionFunc = function(type, obj) {
var func = false;
if(funcRegister[type])
func = funcRegister[type](obj);
return func;
}
Populate your register with functions:
funcRegister['yourtype1'] = function(obj) {
console.log('your type 2');
return obj;
}
funcRegister['yourtype2'] = function(obj) {
console.log('your type 2');
return obj;
}
Then call it with your type and an object where you can put your args
callReflectionFunc(type, obj);
Upvotes: 0
Reputation: 58271
EVAL: http://www.w3schools.com/jsref/jsref_eval.asp
Eval will allow you to run any javascript code by passing in a string and having the javascript engine evaluate it as javascript code.
If you mean that you want to first search a list properties of an object, then look at this:
var o = {}
for(att in o){
alert(o[att]);
}
If you do this, you can even set the property's value by accessing it as if it were an array (all objects are actually associative arrays).
obj["propertyName"] = "new value";
obj["MethodName"]();
Upvotes: 4
Reputation: 10716
In JavaScript, object methods are really just properties containing functions. Like all properties, you can refer to them using associative array syntax:
var x = { 'a': 1 };
x.a += 1;
x['a'] += 1;
console.log(x.a);
Output is: 3
.
So if you have the name of a method you want to invoke on myObject
:
var methodName = 'myMethod';
// Invoke the value of the 'myMethod' property of myObject as a function.
myObject[methodName]();
Upvotes: 7