puk
puk

Reputation: 16782

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.

Upvotes: 2

Views: 5668

Answers (3)

Shaz
Shaz

Reputation: 15867

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

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

Upvotes: 9

Felix Kling
Felix Kling

Reputation: 816404

In the browser, the global object is window [docs]. If you use another JavaScript execution environment (like Node.js), have a look at its documentation to find out the name/reference to the global object.

Of course such a test only works for functions which are defined in global scope, not in any higher scope. So it might be that such a function is available (and accessible) but it is not in the global scope.

Upvotes: 0

scrappedcola
scrappedcola

Reputation: 10572

The Globalcontext is window. All objects are attached to it.

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

Upvotes: 0

Related Questions