Home >Web Front-end >JS Tutorial >JavaScript implements a method similar to getClass() in Java to obtain the object class name_javascript skills
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.