2

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.

3 Answers 3

9

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

function load(functionName){
  if (typeof window[functionName] != 'undefined'){
   window[functionName](arg1 , arg2 , ...);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The question is about calling a global function using it's name as a string, that's why it's not "just as good" as just calling the function as an object.
@katspaugh: That's why I removed it. ;)
I'll accept this as the answer as it is the best response. Quick question, what percent of javascript viewings are down via a browser? 99%? 50%? more, less?
0

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

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

1 Comment

As a few people pointed out this is not always the case (Although it probably is 99% of the time)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.