javascript type 검사 좀더 정교하게

자바스크립트 타입검사시에 보통 typeof 기선언함수를 사용해서 판별하는데 많은 문제가 있다

예를들면

 

alert(typeof []);
//결과 Object
alert(typeof {});
//결과 Object

 

 

좋은 방법은

Object.prototype.toString.call([])
//[object Array] 반환
Object.prototype.toString.call({})
//[object Object] 반환

 

 

하지만 속도 문제가 생길 수 있으니 테스트

 

var isFunction = function(t) {
if (Object.prototype.toString.call(t) == '[object Function') {
return true;
} else {
return false;
}
};

var isFunctionTypeof = function(t) {
if (typeof t == 'Function') {
return true;
} else {
return false;
}
};

var isFunctionConst = function(t) {
if (t.constructor == Array) {
return true;
} else {
return false;
}
};


var test = function(fn, p) {
var startTime = (new Date).getTime();
for (var i = 1; i < 100000; i++) {
fn(p);
}
endTime = (new Date).getTime();
return endTime - startTime;
}


//테스트 (Athlon64 3800+에서)
test(isFunction, 1); //265ms
test(isFunctionTypeof, 1); //59ms
test(isFunctionConst, 1); //233ms

 

한페이지 내에서 타입검사를 100000번이나 할 일이 없으므로

타입검사는 정확한 방법을 쓰는것이 좋겠다.

 

 

 

2009/01/30 21:31 2009/01/30 21:31
juniac
javascript 2009/01/30 21:31

트랙백 주소 : http://juniac.net/trackback/176

  1. typeof 정확한 판별 tracked from Webee - Bastet 2009/11/26 16:26  삭제

    @http://www.juniac.net/176 function typeoftostr(o) { return Object.prototype.toString.call(o); } document.write(typeoftostr("dfdf")); document.write(typeoftostr([])); document.write(typeoftostr({})); document.write(typeoftostr(1)); document.write(typeof..

댓글을 달아 주세요

[로그인][오픈아이디란?]

Powerd by Textcube, designed by criuce