• 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(){}));        //定义一个自定义构造函数
  • 相关阅读:
    java基础高级
    Elasticsearch
    Nginx
    go语言基础
    elasticsearch启动失败
    redis基础
    数据结构(java版)
    mysql实现两个字段合并成一个字段查询
    StringBuffer 字符串截取从后往前,从前往后
    ERROR c.j.e.m.g.h.GatewayExceptionHandler [handle,52] [网关异常处理]请求路径
  • 原文地址:https://www.cnblogs.com/alantao/p/5861663.html
Copyright © 2020-2023  润新知