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.
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.
Share Improve this question edited Dec 22, 2009 at 19:15 7wp asked Dec 22, 2009 at 19:09 7wp7wp 12.7k20 gold badges78 silver badges107 bronze badges4 Answers
Reset to default 7In 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]();
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"]();
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();
};
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);