자바스크립트에는 해당 객체값에 대한 타입을 얻는 예약어로 typeof를 지원합니다. 그러나 요놈이 그다지 정확치 않는 녀석인지라 이보다 더 정확한 타입을 얻을 필요가 있을 시에 다음 함수를 사용할 수 있습니다.
function getType(x) {
if (x == null) {
return 'null';
}
var t = typeof x;
if (t != "object") {
return t;
}
var c = Object.prototype.toString.apply(x);
c = c.substring(8, c.length - 1); // [object ?]의 특성을 이용함
if (c != "Object") {
return c;
}
if (c.constructor == "Object") {
return c;
} else {
var s = x.constructor.toString();
var i = s.indexOf("(");
return s.substring(9, i); // function ?( ... 의 특성을 이용함
}
return "unknown type";
}
위의 코드에 대한 테스트는 아래와 같습니다.
function CTR(a) {
this.a = a;
};
document.write(typeof CTR + " , " + getType(CTR));
var c = new CTR(1);
document.write(typeof c + " , " + getType(c));
document.write(typeof new Date() + " , " + getType(new Date()));
document.write(typeof new Array() + " , " + getType(new Array()));
document.write(typeof 1 + " , " + getType(1));
document.write(typeof "hi" + " , " + getType("hi"));
document.write(typeof this.document + " , " + getType(this.document));
실행 결과는 다음과 같습니다.

실행결과에 대한 각 라인의 첫번째는 자바스크립트에서 제공하는 typeof를 사용한 것이고 두번째는 보다 더 정확한 타입을 얻을 수 있는 getType 함수를 사용한 것입니다.
