Call a JavaScript function name using a string?

Viewed 62752

How can I hook up an event to a function name I have defined as a string?

I'm using Prototype.js, although this is not Prototype-speficic.

$(inputId).observe('click', formData.fields[x].onclick);

This would result in JavaScript complaining that my handler is not a function. I would prefer not us use eval().

10 Answers

Property accessors can be used to access any object's properties or functions.

If the function is in the global scope, you can get it using the window object:

var myFunc = window[myFuncName];

This also works within the this scope:

var myFunc = this[myFuncName];
window.myFunction === window["myFunction"]

Looks like formData.fields[x].onclick holds the name of a global function? If so try:

$(inputId).observe('click', window[formData.fields[x].onclick]);

Do you know what the onclick property contains or what type it is? I assume this is prototype specific stuff, as "fields" does not exist in DOM forms.

Related