obtaining the class name of an Javascript Object





2
Date Submitted Thu. Aug. 20th, 2009 9:53 AM
Revision 1 of 1
Scripter Cloudgen
Tags classname | JavaScript | javascript-object
Comments 0 comments
To obtain the classname of every type of javascript object. See discussion

function getClassName(obj){
        var ret="";
        if(obj==null) return (obj===null)?"null": typeof obj;
        if(/\[native code\]|source code not available/.test(""+obj)) return "##native function";
        if(typeof obj.alert!="undefined") return "##window";
        if(typeof obj.nodeName!="undefined") return "#"+obj.nodeName.toLowerCase();
        (""+obj.constructor).replace(/function\s*([^\(]*)\([^\)]*\)[\s\S]+/,function(s,t){ret=t;return ""});
        if(ret=="Array" && Object.prototype.toString.call(obj)=="[object Object]") ret="Object"
        if(ret=="Number" && isNaN(obj)) return "NaN";
        if(ret==""){
                if (navigator.appName.indexOf("Internet Explorer")>-1){
                        // function names cannot be obtained from ie
                } else for(var i in self){
                        if(Object.prototype.toString.call(self[i])=="[object Function]"){
                                try{    //handle exception in Opera
                                        if(obj instanceof self[i]) {
                                                ret=i;
                                                break;
                                        }
                                } catch(e){};
                        }
                }
        }
        return (ret=="")?"##anonymous class":ret;
}
 

Comments

There are currently no comments for this snippet.

Voting

Votes Up


Scripter Cloudgen
Scripter Dekion

Votes Down