为什么要使用typeof来识别功能? [英] Why use typeof for identifying a function?

查看:46
本文介绍了为什么要使用typeof来识别功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用的重要理由

typeof variable === 'function'

!!variable.call

用于检测变量是否为函数?

for detecting if a variable is a function?

除了显而易见的有人可以创建类似以下对象的对象之外:

Other than the obvious one that someone may create an object like:

{ call: 1 }

我的问题是

typeof /regex/ === 'function'

返回true,但是

!!/regex/.call

返回假

推荐答案

最安全的方法是通过将对象设置为 thisArg 参数来检查内部[[Class]]属性调用 Object.prototype.toString 时> .call()方法.

The safest way is to check the internal [[Class]] property by setting the object as the thisArg argument of the .call() method when calling Object.prototype.toString.

Object.prototype.toString.call( myVariable ) === '[object Function]';

当然,您可以轻松地使用它来实现一个功能:

Of course you could easily make a function out of it:

function checkClass( obj ) {
    return Object.prototype.toString.call( obj ).slice( 8, -1).toLowerCase();
}

checkClass( myVariable ) === 'function';

这很简单,可能会有一些改进,但是您明白了.

This is very simple, and there could be some improvements, but you get the idea.

这篇关于为什么要使用typeof来识别功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆