最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Finding if FunctionClass exists before calling it - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share asked Jul 12, 2011 at 20:34 pukpuk 16.8k31 gold badges124 silver badges205 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

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)

  1. 暂无评论