确定静态命名的 JavaScript 函数是否存在以防止错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7559520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if statically named JavaScript function exists to prevent errors
提问by macintosh264
I have a script on my website that calls a staticallynamed 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?
该childLoad()
函数虽然总是被调用,但并不总是被定义。如果该函数不存在,如何防止脚本调用该函数?
回答by Michael Jasper
if ( typeof childLoad == 'function' ) {
childLoad();
}
回答by Joe
You could use short circuit evaluation:
您可以使用短路评估:
childLoad && childLoad();
编辑
('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.
这将确保childLoad
可以被引用,确保它不是未定义的,然后调用该函数。它不会检查以确保它是一个函数,但我个人认为不需要。
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.
注意:this
如果您使用call
或,则可能不是您所指的上下文apply
。这真的取决于你的代码的其余部分。
回答by Jayendra
if(typeof childLoad == 'function') {
childLoad();
}
回答by Samich
You can simply check:
您可以简单地检查:
if (childLoad)
childLoad()
回答by jcvandan
You could surround it in a try catch!
你可以用try catch包围它!
回答by Mohammed Shafeek
<script>
/* yourfunction */
if(typeof yourfunction == 'function') {
yourfunction();
}
function yourfunction(){
//function code
}
</script>