Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:48:53
Original
1768 people have browsed it

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

Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template