How to get a JavaScript object's class?

前端 未结 18 2333
一生所求
一生所求 2020-11-22 15:44

I created a JavaScript object, but how I can determine the class of that object?

I want something similar to Java\'s .getClass() method.

18条回答
  •  执念已碎
    2020-11-22 16:17

    Agree with dfa, that's why i consider the prototye as the class when no named class found

    Here is an upgraded function of the one posted by Eli Grey, to match my way of mind

    function what(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;
    }
    

提交回复
热议问题