如何检查函数是否已定义?
用于检查函数是否存在的Javascript函数。
使用jQuery.isFunction(),您可以测试一个参数来检查它是否是(a)定义的,(b)是“函数”类型。既然你要求使用jQuery,这个函数就会让你感到满意。
jQuery.isFunction(YourFunction)
如果你因为某种原因不想使用jQuery,这里有一个基于Idealog代码的准系统函数,它将检查变量是否为function
类型。
function isFunction(fn){
return typeof fn === 'function'
}
有时你已经知道它是一个函数,为了优化,没有理由重新检查它的类型,在这种情况下,这里的函数只是检查是否定义了variable
[可能是一个函数]
function isDefined(foo){
return typeof(foo) !== 'undefined'
}
如何使用这些功能
使用jQuery:
function foo(){}
if(jQuery.isFunction(foo)) alert('This is a function');
使用上面提供的任何非jQuery Javascript函数。根据使用环境,这些功能可能是可靠的,也可能是不可靠的。请参阅以下内容
function foo(){}
if(isFunction(foo)) alert('is of type function');
if(isDefined(foo)) alert('if this is a function, it is defined');
检查未定义和使用jQuery.isFunction
if (typeof myfunc !== 'undefined' && $.isFunction(myfunc)) {
//do something
}
jQuery.isFunction()是否优越?
根据Kyle Florence jQuery.isFunction()
,它在某些情况下可能更优越。在使用jQuery方法的某些边缘情况下特别有用,请参阅他的explanation。
在某些浏览器的某些情况下,事物作为“函数”类型被错误地返回,或者事实上函数的事物作为另一种类型返回。你可以在这里看到几个测试用例:https://github.com/jquery/jque ......
一个例子:
var obj = document.createElement(“object”);
// Firefox说这是一个函数类型的obj; // =>“功能”
请记住,这些主要是边缘情况,但$ .isFunction的原因只是为了对某个函数的某些东西持肯定态度(这对于jQuery库本身来说非常重要,可能对你的代码来说不是那么重要)。
感谢patrick dw指出Kyles文章。 (Patrick DW删除了他的账号)
注意:从jQuery 1.3开始,浏览器提供的函数(如alert()和DOM元素方法(如getAttribute())不能保证在Internet Explorer等浏览器中被检测为函数。
这是我用来检查函数是否已经定义的内容:
qazxswpoi
像这样:
if (typeof myFunc != 'undefined') {
// Assign myFunc
}
不要只针对undefined
进行测试,if (typeof(functionName) == 'function') {
}
不是常数,可以重新分配。
if (myFunc !== undefined) {
// myFunc is defined
foo();
}
.
if (myFunc === undefined) {
// myFunc is not defined
qux();
}
要么
if ( typeof(youerFunctionName) === 'undefined' )
{
console.log('undefined');
}
typeof返回字符串,因此您可以使用JavaScript typeof运算符来查找JavaScript变量的类型。
if ([function] != undefined) {
[do stuff]
}
jQuery's isFunction()
您也可以使用func
进行检查。
说你的功能叫做if (func) {
// Function is already defined (or at least something is defined there)
} else {
// Function is not defined
}
:
/*********************************/
if(typeof(callback) == 'function')
/*********************************/
试试这个
example
这是一个工作的function test(){}
if(typeof test != "undefined")
// function is allready defined
if ( typeof(myFunc()) === 'undefined' )
{
console.log('myFunc undefined');
}
else
{
console.log('myFunc defined');
}