为啥jQuery是用toString来判断数据类型,而不是typeof或instanceof

为什么jQuery是用toString来判断数据类型,而不是typeof或instanceof

// Numbers
typeof37 === 'number';
typeof3.14 === 'number';
typeofMath.LN2 === 'number';
typeofInfinity === 'number';
typeofNaN === 'number';// Despite being "Not-A-Number"
typeofNumber(1) === 'number';// but never use this form!
 
// Strings
typeof"" === 'string';
typeof"bla" === 'string';
typeof(typeof1) === 'string';// typeof always return a string
typeofString("abc") === 'string';// but never use this form!
 
// Booleans
typeoftrue === 'boolean';
typeoffalse === 'boolean';
typeofBoolean(true) === 'boolean';// but never use this form!
 
// Undefined
typeofundefined === 'undefined';
typeofblabla === 'undefined';// an undefined variable
 
// Objects
typeof{a:1} === 'object';
typeof[1, 2, 4] === 'object';// use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeofnew Date() === 'object';
typeofnull === 'object';
 
typeofnew Boolean(true) === 'object';// this is confusing. Don't use!
typeofnew Number(1) === 'object'; // this is confusing. Don't use!
typeofnew String("abc") === 'object'; // this is confusing. Don't use!
 
// Functions
typeoffunction(){} === 'function';
typeofnew Function() === 'function';
typeofMath.sin === 'function';
从上面的例子可知,typeof不能判断出数组和null,而且对于通过new操作符生成的对象,也无法判断类型。

至于instanceof,因为在JavaScript中,所有对象都是object,也就是说new Number(2)或new String('hello')也是object,故无法判断。

但Object.prototype.toString对任何变量会永远返回这样一个字符串"[object class]",而这个class就是JavaScript内嵌对象构造函数的名字。至于用户自定义的变量,则class等于object。因此通过Object.prototype.toString.apply(obj)可以准确的获取变量数据类型。通过Object.prototype.toString可以获得的数据类型包括:Date, Object, String, Number, Boolean, Regexp, Function, undefined, null, Math等。