1. toString.call() 이란?
toString.call(value)은 객체의 정확한 타입을 판별하는 방법 중 하나이다.
이는 Object.prototype.toString() 메서드를 활용하여 모든 JavaScript 값의 내부 [[Class]]를 반환하는 방식으로 동작한다.
2. toString.call()의 동작 원리
기본적으로, JavaScript에서 Object.prototype.toString() 메서드는 객체를 문자열로 변환하는 기능을 한다.
하지만 이를 call()과 함께 사용하면 객체의 정확한 타입을 판별하는 도구로 활용할 수 있다.
🔹 기본적인 toString.call() 사용 예시
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call("Hello")); // "[object String]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call({})); // "[object Object]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(new Date())); // "[object Date]"
console.log(Object.prototype.toString.call(/regex/)); // "[object RegExp]"
console.log(Object.prototype.toString.call(() => {})); // "[object Function]"
console.log(Object.prototype.toString.call(Symbol())); // "[object Symbol]"
console.log(Object.prototype.toString.call(BigInt(10))); // "[object BigInt]"
👀 반환 형식:
"[object 타입]" 형식으로 반환된다.
3. typeof vs toString.call() 차이점
JavaScript에서 객체의 타입을 확인하는 방법으로 typeof와 toString.call() 이 있다.
하지만 typeof는 객체의 정확한 타입을 반환하지 못하는 경우가 많다.
값 | typeof 결과 | toString.call() 결과 |
123 | "number" | "[object Number]" |
"hello" | "string" | "[object String]" |
true | "boolean" | "[object Boolean]" |
null | "object" (버그) | "[object Null]" |
undefined | "undefined" | "[object Undefined]" |
[] | "object" | "[object Array]" |
{} | "object" | "[object Object]" |
() => {} | "function" | "[object Function]" |
/regex/ | "object" | "[object RegExp]" |
🔹 typeof의 한계점
• null의 타입이 "object"로 출력되는 오래된 버그가 있다.
• typeof로는 배열(Array)과 객체(Object)를 구분할 수 없다.
• 정규 표현식(RegExp), 날짜(Date) 등을 식별할 수 없다.
🔹 toString.call()의 장점
• 모든 값의 정확한 타입을 반환할 수 있다.
• null과 undefined도 정확히 구분할 수 있다.
• Array, RegExp, Date 등도 판별할 수 있다.
4. toString.call() 활용 사례
1) 배열(Array) 판별하기
JavaScript에서는 typeof를 사용하면 배열과 객체를 구별할 수 없다.
console.log(typeof []); // "object" (배열인지 객체인지 알 수 없음)
하지만 toString.call()을 사용하면 확실하게 배열을 구분할 수 있다.
console.log(Object.prototype.toString.call([])); // "[object Array]"
이 방법은 Array.isArray()를 사용할 수 없는 환경에서 유용할 수 있다.
2) null과 undefined 판별하기
typeof를 사용하면 null이 "object"로 잘못 인식된다.
console.log(typeof null); // "object" (버그)
console.log(typeof undefined); // "undefined"
하지만 toString.call()을 사용하면 정확하게 판별할 수 있다.
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
3) 사용자 정의 타입 체크
toString.call()을 사용하면 객체가 특정 타입인지 쉽게 확인할 수 있다.
function isDate(value) {
return Object.prototype.toString.call(value) === "[object Date]";
}
console.log(isDate(new Date())); // true
console.log(isDate("2024-02-11")); // false
4) 여러 타입을 한 번에 체크하는 유틸 함수 만들기
다양한 타입을 체크할 수 있는 함수를 만들 수 있다.
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
console.log(getType(123)); // "Number"
console.log(getType("hello")); // "String"
console.log(getType([])); // "Array"
console.log(getType({})); // "Object"
console.log(getType(null)); // "Null"
console.log(getType(() => {}));// "Function"
위 코드는 "[object 타입]"에서 "타입" 부분만 추출하여 반환한다.
5. toString.call()을 사용하지 않는 경우
최근에는 toString.call() 대신 아래와 같은 방법을 사용할 수도 있다.
✅ Array.isArray() 사용 (배열 판별)
배열을 판별할 때 Array.isArray()를 사용하면 더 간단하다.
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false
✅ instanceof 연산자 사용
instanceof는 객체가 특정 클래스의 인스턴스인지 확인하는 데 사용할 수 있다.
console.log([] instanceof Array); // true
console.log(new Date() instanceof Date); // true
console.log({} instanceof Object); // true
하지만 instanceof는 같은 JavaScript 환경에서 생성된 객체에 대해서만 동작한다.
예를 들어, 다른 iframe에서 생성된 객체는 instanceof가 제대로 동작하지 않을 수도 있다.
6. 결론
✅ toString.call()은 JavaScript의 모든 값에 대해 정확한 타입을 반환하는 방법이다.
✅ typeof보다 더 정확하게 null, Array, Date, RegExp 등을 판별할 수 있다.
✅ 최근에는 Array.isArray()나 instanceof 같은 대체 방법도 있지만, toString.call()은 가장 범용적인 해결책이다.
JavaScript에서 모든 값을 안전하게 타입 체크하고 싶다면 Object.prototype.toString.call(value)을 사용하자!
'BACKEND [Kamranahmedse Roadmap] > JavaScript' 카테고리의 다른 글
[JS] 호이스팅(Hoisting)이란? (0) | 2025.02.15 |
---|---|
[JS] 함수 선언문 vs 함수 표현식 (0) | 2025.02.14 |
[JS] 반복문 비교: forEach, for in, for of 차이점 완벽 정리 (0) | 2025.02.14 |
[JS] JavaScript의 동적 타입(Dynamic Typing) 완전 정리 (0) | 2025.02.12 |
[JS] 기본 문자열 vs String 객체 (0) | 2024.11.13 |