How do I call a dynamically-named method in Javascript?

Chris B picture Chris B · Jun 9, 2009 · Viewed 125.4k times · Source

I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.

The JavaScript will be used to populate a listbox based on the selection in another listbox. When the selection of one listbox is changed it will call a method name based on the selected value of the listbox.

For example:

Listbox1 contains:

  • Colours
  • Shapes

If Colours is selected then it will call a populate_Colours method that populates another listbox.

To clarify my question: How do I make that populate_Colours call in JavaScript?

Answer

Triptych picture Triptych · Jun 9, 2009

Assuming the populate_Colours method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window host object.

var method_name = "Colours";
var method_prefix = "populate_";

// Call function:
window[method_prefix + method_name](arg1, arg2);