javascript實(shí)現(xiàn)類似java中g(shù)etClass()得到對(duì)象類名的方法
本文實(shí)例講述了javascript實(shí)現(xiàn)類似java中g(shù)etClass()得到對(duì)象類名的方法。分享給大家供大家參考。具體如下:
在javascript中沒有能夠返回特定類型名的函數(shù)
如一個(gè)對(duì)象 console.log(obj);
得到的是[object HtmlTableCellElement]如果想要一個(gè)函數(shù)能夠返回HtmlTableCellElement js中默認(rèn)沒有這樣的函數(shù) 可以自己實(shí)現(xiàn)一個(gè)
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;
};
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。
相關(guān)文章
JavaScript實(shí)現(xiàn)的in_array函數(shù)
這篇文章主要介紹了JavaScript實(shí)現(xiàn)的in_array函數(shù),用于判斷一個(gè)值是否在數(shù)組中,類似PHP的in_array函數(shù),需要的朋友可以參考下2014-08-08
TypeScript?mixin提升代碼復(fù)用性的方法和原理
在前端開發(fā)中,我們經(jīng)常需要在不同的組件或類之間共享功能代碼,Mixin提供了一種非常靈活的方式,可以讓我們在不破壞繼承關(guān)系的前提下,將功能代碼復(fù)用到多個(gè)對(duì)象中,文章通過代碼示例介紹mixin提升代碼復(fù)用性的方法和好處,需要的朋友可以參考下2023-06-06
JavaScript高級(jí)程序設(shè)計(jì)閱讀筆記(五) ECMAScript中的運(yùn)算符(一)
ECMAScript中的運(yùn)算符,學(xué)習(xí)js的朋友可以看看2012-02-02

