SoFunction
Updated on 2025-04-06

JavaScript implements a method similar to getClass in Java to get object class name

This article describes the method of JavaScript implementing a method similar to getClass() in Java to get object class name. Share it for your reference. The details are as follows:

There is no function in javascript that can return a specific type name

Such as an object (obj);
What I got is [object HtmlTableCellElement] If you want a function to return HtmlTableCellElement, there is no such function in js by default. You can implement one by yourself.

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

I hope this article will be helpful to everyone's JavaScript programming.