如何检查jQuery中的函数是否为空?

时间:2012-08-02 16:38:12

标签: jquery function

如何检查确实存在和定义的函数是否为空?例如:

function foo(){
   // empty
}

function bar(){
   alert('something');
   // not empty
}

是否有功能或简单的方法来检查这个?

2 个答案:

答案 0 :(得分:3)

这不是非常有用,通常不是一个好主意,但你可以这样做:

function foo(){

}

function bar(){
   alert('something');
   // not empty
}

console.log('foo is empty :' + isEmpty(foo));
console.log('bar is empty :' + isEmpty(bar));

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "")
   )[1].trim() === "";
}​

FIDDLE

如果只是检查一个回调,通常的方法就是检查回调是否是一个函数:

if (typeof callback === 'function') callback.call();

修改

也无视评论:

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
   )[1].trim() === "";
}​

FIDDLE

答案 1 :(得分:1)

函数可以为空但仍然是传递变量。这在adeneo的功能中会出错:

function bar(t) { }

修改正则表达式,这里是支持变量的相同函数:

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\([^)]\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
   )[1].trim() === "";
}​