Get the name of an object's type

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

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

20条回答
  •  无人及你
    2020-11-21 22:58

    Update

    To be precise, I think OP asked for a function that retrieves the constructor name for a particular object. In terms of Javascript, object does not have a type but is a type of and in itself. However, different objects can have different constructors.

    Object.prototype.getConstructorName = function () {
       var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();
       var cname = str.match(/function\s(\w*)/)[1];
       var aliases = ["", "anonymous", "Anonymous"];
       return aliases.indexOf(cname) > -1 ? "Function" : cname;
    }
    
    new Array().getConstructorName();  // returns "Array"
    (function () {})().getConstructorName(); // returns "Function"
    

     


    Note: the below example is deprecated.

    A blog post linked by Christian Sciberras contains a good example on how to do it. Namely, by extending the Object prototype:

    if (!Object.prototype.getClassName) {
        Object.prototype.getClassName = function () {
            return Object.prototype.toString.call(this).match(/^\[object\s(.*)\]$/)[1];
        }
    }
    
    var test = [1,2,3,4,5];
    
    alert(test.getClassName()); // returns Array
    

提交回复
热议问题