存在して定義されている関数が空かどうかをどのように確認しますか? 例えば:
function foo(){
// empty
}
function bar(){
alert('something');
// not empty
}
これを確認する関数または簡単な方法はありますか?
これはあまり有用ではなく、一般的には良い考えではありませんが、次のことができます。
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() === "";
}
コールバックをチェックするだけの場合、通常の方法は、コールバックが関数であるかどうかをチェックすることです。
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() === "";
}
関数は空でも、変数を渡すことができます。これは、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() === "";
}