开发者

Determine if statically named JavaScript function exists to prevent errors

I have a script on my website that calls a statically na开发者_如何学Gomed function when called:

childLoad();

The childLoad() function is not always defined though it is always called. How can I prevent the script from calling this function if it does not exist?


if ( typeof childLoad == 'function' ) { 
    childLoad(); 
}


You could use short circuit evaluation:

childLoad && childLoad();


EDIT

('childLoad' in this) && childLoad && childLoad();

This will make sure childLoad can be referenced, makes sure it's not undefined, then call the function. It doesn't check to make sure it is a function, but I personally feel that is not needed.

NOTE: this might not be the context you are referring to if you are using call or apply. It really depends on the rest of your code.


if(typeof childLoad == 'function') {   
  childLoad();   
}


You can simply check:

if (childLoad)
    childLoad()


You could surround it in a try catch!


<script>
/* yourfunction */
if(typeof yourfunction == 'function') {   
  yourfunction();   
}
function yourfunction(){
  //function code
}
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜