为什么使用toString()来检查你可以用typeof检查的args?

时间:2012-03-01 08:10:40

标签: javascript types typechecking

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

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

在数组的情况下非常清楚,因为您无法使用typeof来检查数组。 Valentine使用instanceof

ar instanceof Array

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

jQueryUnderscore都使用类似的方法来检查功能:

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

这不等于这样做吗?

typeof obj === 'function'

甚至是这个?

obj instanceof Function

2 个答案:

答案 0 :(得分:16)

好的,我想我找出了为什么你会看到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]

答案 1 :(得分:1)

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

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

但是,正如您所建议的那样,如果您希望某些字符串或其他类型与typeof一致,我认为没有理由不能使用typeof(我经常这样做)在这种情况下使用typeof

你提到的那些库使用他们选择的方法的另一个原因可能只是为了保持一致性。您可以使用typeof来检查Array,因此请使用其他方法并始终坚持这一点。

有关更多信息,请Angus Croll has an excellent article on the typeof operator