请问这个 `getType` 是一个函数吗

学习Javascript的过程中,遇到了下面的问题:

我需要封装一个判断对象类型的函数 getType,得到的结果不合人意,如下:

const getType = Object.prototype.toString.call

// 判断 target 的类型
getType(target)

// Uncaught TypeError: getType is not a function
阅读 2.3k
2 个回答

这是一个很特殊的问题,居然真有人遇到了

我们知道 Function 的原型链上有三个方法 .bind .call .apply
事实上,你对这三个方法进行你给出代码里的操作,都是会报错的:

function f () {
}
const bind = f.bind
const call = f.call
const apply = f.apply

bind()    // TypeError: Bind must be called on a function
call()    // TypeError: call is not a function
apply()   // TypeError: apply is not a function

为什么会这样?其实我们可以从 bind() 的错误信息中看出一点提示:.bind() .call() .apply() 这三个方法必须由一个函数为主体进行调用
意思是说,这三个方法的使用,必须是 func.bind() func.call() func.apply() 这种形式,把它单独赋值给一个变量去调用是不行的。
至于原因,仔细想想这三个方法的作用体会一下。

如果你需要封装这样一个 getType 的话,可以像楼上给出的方案那样:

const getType = target => Object.prototype.toString.call(target)

希望对你有帮助

const getType = target => Object.prototype.toString.call(target);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题