type()方法实现的依据

方法

    Object.prototype.toString.call(参数)

常见的值

var number = 1;          // [object Number]
var string = '123';      // [object String]
var boolean = true;      // [object Boolean]
var und = undefined;     // [object Undefined]
var nul = null;          // [object Null]
var obj = {a: 1}         // [object Object]
var array = [1, 2, 3];   // [object Array]
var date = new Date();   // [object Date]
var error = new Error(); // [object Error]
var reg = /a/g;          // [object RegExp]
var func = function a(){}; // [object Function]

console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]

function a() {
    console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
}

一些有趣的细节

var str = 'str' 
var str2 = new String('str')

typeof str  //string
typeof str2 // object

Object.prototype.toString.call(str) //"[object String]"
Object.prototype.toString.call(str2) //"[object String]"
Comments
Write a Comment