开发者

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'] != 'undefine开发者_运维技巧d'){...}

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.


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

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


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜