为什么要使用toString()来对可以使用typeof进行检查的参数进行类型检查

Why use toString() to typecheck args that you can check with typeof?

本文关键字:参数 进行检查 检查 类型 typeof toString 为什么 可以使      更新时间:2023-09-26

我理解为什么需要使用Object.prototype.toString()String()进行类型检查数组,但typeof是否足以进行类型检查函数和字符串?例如,Array.isArray的MDN上的polyfill使用:

Object.prototype.toString.call(arg) == '[object Array]';

在数组的情况下,这一点非常清楚,因为您不能使用typeof来检查数组。Valentine使用实例:

ar instanceof Array

但是对于字符串/函数/布尔值/数字,为什么不使用typeof呢?

jQuery和Undercore都使用类似的东西来检查函数:

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

这难道不等于这样做吗?

typeof obj === 'function'

甚至是这个?

obj instanceof Function

好吧,我想我已经明白了为什么你会看到toString的用法。考虑一下:

var toString = Object.prototype.toString;
var strLit = 'example';
var strStr = String('example')​;
var strObj = new String('example');
console.log(typeof strLit); // string    
console.log(typeof strStr); // string
console.log(typeof strObj); // object
console.log(strLit instanceof String); // false
console.log(strStr instanceof String); // false
console.log(strObj instanceof String); // true
console.log(toString.call(strLit)); // [object String]
console.log(toString.call(strStr)); // [object String]
console.log(toString.call(strObj)); // [object String]

我能想到的第一个原因是typeof null返回object,这通常不是你想要的(因为null不是一个对象,而是一个类型)。

但是,Object.prototype.toString.call(null)返回[object Null]

但是,正如您所建议的,如果您希望某个字符串或其他类型能够很好地与typeof配合使用,我认为您没有理由不使用typeof(在这种情况下,我经常使用typeof)。

您提到的库使用所选方法的另一个原因可能只是为了保持一致性。您可以使用typeof来检查Array,因此请使用另一种方法并始终坚持该方法。

有关更多信息,Angus Croll有一篇关于typeof运算符的优秀文章。