Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a JavaScript function name using a string?

Tags:

javascript

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().

like image 712
Diodeus - James MacFarlane Avatar asked Jan 30 '09 19:01

Diodeus - James MacFarlane


People also ask

How do you call a function name my function in JavaScript?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.

How do you name a JavaScript function?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

How do I turn a string into a function?

To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.


1 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]; 
like image 62
Greg Avatar answered Oct 05 '22 20:10

Greg