javascript实现类似java中getClass()得到对象类名的方法_javascript技巧

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

本文实例讲述了javascript实现类似java中getClass()得到对象类名的方法。分享给大家供大家参考。具体如下:

在javascript中没有能够返回特定类型名的函数

如一个对象 console.log(obj);
得到的是[object HtmlTableCellElement]如果想要一个函数能够返回HtmlTableCellElement js中默认没有这样的函数 可以自己实现一个

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

希望本文所述对大家的javascript程序设计有所帮助。

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!