타입 잘 감별하기

개발.log·2023년 3월 16일
2

<타입 잘 판단하기>

첫 번째로 제일 많이 사용하는 typeof는 무적이 아니다.

  1. typeof
OK!
typeof '문자열' //'string'
typeof true //boolean
typeof undefined //undefined
typeof 123 //number
typeof Symbol() //symbol
ERROR!
typeof function myFunction(){} //function
typeof class MyClass {} //function
typeof const str = new String('문자열') // object
typeof null //object

→ PRIMITIVE값은 잘 판단하지만, REFERNCE(object류,, array, function, Date, 등등..)은 잘 판별 못함.

  1. instanceof
OK!
const arr = [];
const func = function() {}
const date = new Date();

arr instanceof Array //true;
func instanceof Function //true;
date instanceof Date //true
ERROR!
arr instanceof Object //true;
func instanceof Object //true;
date instanceof Object //true

→ reference type의 프로토타입을 올라가다보면 최상의에 Object가 있다. 따라서, 타입 검사의 어려움..
그렇다면? Object prototype chain을 타는 것을 역이용한다.

  1. Object.prototype.[object].call()
OK!
const arr = [];
const func = function() {}
const date = new Date();

Object.prototype.toSring.call(’’) // ’[object String]’
Object.prototype.toString.call(new String('')) // ’[object String]’
Object.prototype.toString.call(arr) // ’[object Array]’
Object.prototype.toString.call(func) // ’[object Function]’
Object.prototype.toString.call(date) // ’[object Date]’
profile
Think Big Aim High Act Now

0개의 댓글