Object.prototype.toString()

Object.prototype.toString()方法返回一个代表该对象的字符串。

var o = new Object();
o.toString();           //"[object Object]"

 

使用toString()方法来检测对象类型

var toString = Object.prototype.toString;
toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript ES5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]

 

封装为classof()函数

function classof(o){
    if(o === null) return "Null";
    if(o === undefined) return "Undefined";
    //Object.prototype.toString()返回"[object Object]",然后call(o)参数,返回该类型,如number类型call(1),返回"[object Number]",再使用slice(截取类型部分)
    return Object.prototype.toString.call(o).slice(8,-1);       
}
console.log(classof(null));                  //"Null"
console.log(classof(undefined));             //"Undefined"
console.log(classof(1));                     //"Number"
console.log(classof(""));                    //"String"
console.log(classof(true));                  //"Boolean"
console.log(classof({}));                    //"Object"
console.log(classof([]));                    //"Array"
console.log(classof(new Date()));            //"Date"
console.log(classof(/./));                   //"RegExp"
console.log(window);                         //window(这是客户端宿主对象)
console.log(classof(function f(){}));        //定义一个自定义构造函数

 

posted @ 2016-09-11 14:02  AlanTao  阅读(2104)  评论(0编辑  收藏  举报