Object.prototype.toString()

本文介绍了一个实用的方法,通过使用JavaScript的Object.prototype.toString()方法来准确地检测不同类型的对象,包括基本类型和复杂对象,并提供了一个封装好的classof()函数。

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(){}));        //定义一个自定义构造函数

 

转载于:https://www.cnblogs.com/alantao/p/5861663.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值