zoukankan      html  css  js  c++  java
  • 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(){}));        //定义一个自定义构造函数
  • 相关阅读:
    Zephyr网络协议
    Zephyr启动过程与中断响应
    CortexM处理器的一些特性记录
    qemu 使用记录
    Request与Response详解
    http请求头(Header)参数详解
    win10java环境变量配置
    逻辑运算符:与、或、非、异或
    SQL注入相关知识整理
    网页是否存在SQL注入的简单判断
  • 原文地址:https://www.cnblogs.com/alantao/p/5861663.html
Copyright © 2011-2022 走看看