Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Finding if Function/Class exists before calling it

I know how to check to see if a property of the global context exists. Any variation of

if (typeof myFunction != 'undefined'){...}

but what if I don't know the name of the function? I think globally I could do this

if (typeof this['myFunction'] != 'undefined'){...}

but I don't know how to do that in a function like this

function load(functionName){
  if (typeof GLOBALCONTEX[functionName] != 'undefined'){
    GLOBALCONTEX[functionName](arg1 , arg2 , ...);
  }
}

And I don't want to use try/catch as I have heard it is slow.

like image 485
puk Avatar asked Mar 05 '26 17:03

puk


1 Answers

If working with a browser, substitute GLOBALCONTEX with window. Example:

function load(functionName){
  if (typeof window[functionName] != 'undefined'){
   window[functionName](arg1 , arg2 , ...);
  }
}
like image 177
Shaz Avatar answered Mar 08 '26 06:03

Shaz