search

Home  >  Q&A  >  body text

javascript - Print the actual type of a js object

http.createServer((req,res)=>{
    res.write('hello world');
    console.log(typeof res);// obj
    res.end();
});

How to check the specific object types of req and res, so that you can go to the document to see the specific details. api.typeof prints out object, and I hope that what prints out is http.ServerResponse

How to do it

滿天的星座滿天的星座2699 days ago928

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-07-05 10:59:14

    Print the class information of the function:

    function classof(obj){
        if(typeof(obj)==="undefined")return "undefined";
        if(obj===null)return "Null";
        var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
        if(res==="Object"){
            res = obj.constructor.name;
            if(typeof(res)!='string' || res.length==0){
                if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
                if(obj instanceof Array)return "Array";// Array prototype is very sneaky
                return "Object";
            }
        }
        return res;
    }
    
    // Example
    console.log(classof(new Date()));   // => "Date"

    reply
    0
  • Cancelreply