js .isfunction 实现
在 JavaScript 中,可以通过多种方式实现类似 isFunction 的功能来检测一个变量是否为函数类型。以下是几种常见的实现方法:
使用 typeof 操作符
typeof 操作符是检测函数类型的最简单方法。函数在 JavaScript 中被归类为对象,但 typeof 可以区分函数和其他对象类型。
function isFunction(obj) {
return typeof obj === 'function';
}
使用 instanceof 操作符
instanceof 操作符可以检查对象的原型链中是否存在 Function 构造函数。这种方法适用于检查显式定义的函数。
function isFunction(obj) {
return obj instanceof Function;
}
使用 Object.prototype.toString
Object.prototype.toString 方法可以返回对象的类型字符串,对于函数会返回 [object Function]。
function isFunction(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
使用 Function.prototype.isPrototypeOf
Function.prototype.isPrototypeOf 可以检查对象的原型链中是否包含 Function.prototype。
function isFunction(obj) {
return Function.prototype.isPrototypeOf(obj);
}
注意事项
- 箭头函数:上述方法对箭头函数同样有效,因为箭头函数也是
Function的实例。 - 跨框架问题:在多个 iframe 或窗口环境中,
instanceof可能会失效,因为每个环境有独立的Function构造函数。此时推荐使用typeof或Object.prototype.toString。 - 性能:
typeof的性能通常最好,因为它是语言内置的直接操作。
示例代码
以下是一个综合示例,展示如何使用这些方法检测函数:

const func = () => {};
const notFunc = {};
console.log(typeof func === 'function'); // true
console.log(func instanceof Function); // true
console.log(Object.prototype.toString.call(func) === '[object Function]'); // true
console.log(Function.prototype.isPrototypeOf(func)); // true
console.log(typeof notFunc === 'function'); // false
console.log(notFunc instanceof Function); // false
选择哪种方法取决于具体需求,大多数情况下 typeof 已经足够。






