Get the name of an object's type

前端 未结 20 2274
忘掉有多难
忘掉有多难 2020-11-21 22:37

Is there a JavaScript equivalent of Java\'s class.getName()?

20条回答
  •  悲&欢浪女
    2020-11-21 22:55

    I was actually looking for a similar thing and came across this question. Here is how I get types: jsfiddle

    var TypeOf = function ( thing ) {
    
        var typeOfThing = typeof thing;
    
        if ( 'object' === typeOfThing ) {
    
            typeOfThing = Object.prototype.toString.call( thing );
    
            if ( '[object Object]' === typeOfThing ) {
    
                if ( thing.constructor.name ) {
                    return thing.constructor.name;
                } 
    
                else if ( '[' === thing.constructor.toString().charAt(0) ) {
                    typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
                } 
    
                else {
    
                    typeOfThing = thing.constructor.toString().match( /function\s*(\w+)/ );
    
                    if ( typeOfThing ) { 
                        return typeOfThing[1];
                    } 
    
                    else {
                        return 'Function';
                    }
                }
            } 
    
            else {
                typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
            }
        }
    
        return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1);
    }
    

提交回复
热议问题