哪个是检查变量是否是函数的最佳方法?
var cb = function () {
return;
}
if (!!(cb && cb.constructor && cb.apply)) {
cb.apply(somevar, [err, res]);
}
//VS
if (!!(cb && 'function' === typeof cb) {
cb.apply(somevar, [err, res]);
}
Run Code Online (Sandbox Code Playgroud)
最常见的方法是使用:
(typeof foo === 'function')
Run Code Online (Sandbox Code Playgroud)
但是如果你想匹配类似函数的对象(不常见,但很有用),你可以检查该对象是否可调用:
(foo && foo.call && foo.apply)
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您还可以测试构造函数(非常类似于typeof):
(foo.constructor === Function)
Run Code Online (Sandbox Code Playgroud)
如果你想引发异常,你总是可以:
try {
foo();
} catch (e) {
// TypeError: foo is not a function
}
Run Code Online (Sandbox Code Playgroud)