如果函数不存在写函数 - javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8839112/
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
if function does not exist write function - javascript
提问by Bret Thomas
In php I'm writing the following
在 php 中,我正在编写以下内容
<?php
if(x != 0) {
echo "function myfunction(){};";
}
?>
In javascript I wish to test if the function exists and if not write out an empty function
在javascript中,我希望测试该函数是否存在,如果不写出一个空函数
if(typeof myfunction != 'function'){
function myfunction(){};
}
This works great in firefox but, in chrome even if the typeof equals function it still goes into and creates the empty function. I can't find a work around for chrome, i've tried if(!myfunction), if(typeof window.myfunction != 'function) but nothing seems to work here for chrome when everything seems to work in firefox. Any ideas?
这在 Firefox 中效果很好,但是,在 chrome 中,即使 typeof equals 函数仍然进入并创建空函数。我找不到 chrome 的解决方法,我试过 if(!myfunction), if(typeof window.myfunction != 'function) 但是当一切似乎在 Firefox 中都可以正常工作时,chrome 似乎没有任何工作。有任何想法吗?
回答by Quentin
Use a function expression, not a function declaration.
使用函数表达式,而不是函数声明。
if(typeof myfunction != 'function'){
window.myfunction = function(){};
}
(I'm using window
since your last paragraph suggests you want a global function)
(我正在使用,window
因为您的最后一段建议您需要一个全局函数)
回答by Juank
You should use strict comparison operator !==
您应该使用严格的比较运算符 !==
if(typeof myFunction !== 'function'){
window.myFunction = function(){}; // for a global function or
NAMESPACE.myFunction = function(){}; // for a function in NAMESPACE
}
Also try to keep js functions inside namespaces, this way you avoid collisions with other js libraries in the future.
还要尝试将 js 函数保留在命名空间内,这样可以避免将来与其他 js 库发生冲突。