Home >Web Front-end >JS Tutorial >JavaScript implements a method similar to getClass() in Java to obtain the object class name_javascript skills

JavaScript implements a method similar to getClass() in Java to obtain the object class name_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:48:531773browse

The example in this article describes how javascript implements a method similar to getClass() in java to obtain the object class name. Share it with everyone for your reference. The details are as follows:

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

Like an object console.log(obj);
What you get is [object HtmlTableCellElement]. If you want a function that can return HtmlTableCellElement. There is no such function by default in js. You can implement one yourself

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; 
};

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn