faqts : Computers : Programming : Languages : JavaScript : Language Core : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

35 of 37 people (95%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I invoke a function dynamically, if I know its name (as a string. not as function reference)

Jul 22nd, 2002 12:40
Thor Larholm, Jean-Bernard Valentaten, SB S,


A function is an object like any other, and like any other object it 
resides as a property of the intrinsic Global object. In the browser 
environment, the
  window
object serves as the Global object. Otherwise, the keyword
  this
serves as the Global object if none other exist, but only outside 
contructor functions.
  function monkey(sArg){
    alert('monkey was called with this argument:\n' + sArg);
  }
  var sFunctionName = "monkey";
  var oFunc = this[sFunctionName];
  oFunc('hi');
Using this associative array based approach also eliminates the 
needless overhead found with eval, which should be avoided at all costs.