views:

120

answers:

2

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.

+2  A: 

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"]();
Gabriel McAdams
omg of course... eval. I'm an idiot. thank you, i should have thought of that.
Roberto Sebestyen
eval() is a much bigger stick than you need to do what you want. Simply use associative array syntax: `var propName = 'bar'; var x = objectFoo[propName];`
Annabelle
Related note, if the scope of the variable containing the function is "window", you can use parent[var]();
sparkey0
+1  A: 

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]();
Annabelle
My answer had this in it... It had this AND Eval.
Gabriel McAdams