如何判断JavaScript中的函数是否已定义?

我想做这样的事情

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

但是它得到了一个

回调不是函数

未定义回调时发生错误。


当前回答

大多数(如果不是所有)前面的答案都有调用该函数的副作用

以下是最佳实践

你有函数

函数myFunction() { var x = 1; } 直接测试的方法

/ /直接的方式 if((typeof window.myFunction)=='function') alert('myFunction是函数') 其他的 alert('myFunction未定义'); 使用字符串,因此只能在一个位置定义函数名

/ / byString var strFunctionName = ' myFunction ' if((typeof window[strFunctionName])=='function') Alert (s+' is function'); 其他的 警报(s+'未定义');

其他回答

我正在寻找如何检查一个jQuery函数是否被定义,我没有找到它很容易。

也许你会需要它;)

if(typeof jQuery.fn.datepicker !== "undefined")
if ('function' === typeof callback) ...

大多数(如果不是所有)前面的答案都有调用该函数的副作用

以下是最佳实践

你有函数

函数myFunction() { var x = 1; } 直接测试的方法

/ /直接的方式 if((typeof window.myFunction)=='function') alert('myFunction是函数') 其他的 alert('myFunction未定义'); 使用字符串,因此只能在一个位置定义函数名

/ / byString var strFunctionName = ' myFunction ' if((typeof window[strFunctionName])=='function') Alert (s+' is function'); 其他的 警报(s+'未定义');

我可能会

try{
    callback();
}catch(e){};

我知道有一个公认的答案,但没人这么建议。我不确定这是否符合惯用语的描述,但它适用于所有情况。

在较新的JavaScript引擎中,可以使用finally代替。

Try:

if (!(typeof(callback)=='undefined')) {...}