How to get a JavaScript object's class?

前端 未结 18 2175
一生所求
一生所求 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:07

    I find object.constructor.toString() return [object objectClass] in IE ,rather than function objectClass () {} returned in chome. So,I think the code in http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects may not work well in IE.And I fixed the code as follows:

    code:

    var getObjectClass = function (obj) {
            if (obj && obj.constructor && obj.constructor.toString()) {
                
                    /*
                     *  for browsers which have name property in the constructor
                     *  of the object,such as chrome 
                     */
                    if(obj.constructor.name) {
                        return obj.constructor.name;
                    }
                    var str = obj.constructor.toString();
                    /*
                     * executed if the return of object.constructor.toString() is 
                     * "[object objectClass]"
                     */
                     
                    if(str.charAt(0) == '[')
                    {
                            var arr = str.match(/\[\w+\s*(\w+)\]/);
                    } else {
                            /*
                             * executed if the return of object.constructor.toString() is 
                             * "function objectClass () {}"
                             * for IE Firefox
                             */
                            var arr = str.match(/function\s*(\w+)/);
                    }
                    if (arr && arr.length == 2) {
                                return arr[1];
                            }
              }
              return undefined; 
        };
        
    

提交回复
热议问题