자바스크립트 타입(2)

Bonggus·2021년 10월 24일
0

자바스크립트

목록 보기
7/23
post-thumbnail

자바스크립트는 typeof라는 문법을 통해 데이터의 타입을 확인할 수 있다. 하지만, typeof가 모든 것을 알려줄까? 원시값의 경우 문제가 없지만, 레퍼런스 타입의 데이터들은 typeof로 판별할 때 문제가 생길 수 있다.

PRIMITIVE

  • number
  • string
  • boolean
  • null
  • undefined
  • Symbol

REFERENCE(object)

  • array
  • function
  • date
function myFunc() {}
class MyClass {}
const str = new String('문자')

typeof '문자'
typeof true
typeof undefined
typeof 123
typeof Symbol()
typeof myFunc //function
typeof MyClass //function
typeof str // object

치명적문제: null

언어적 오류. 자바스크립트가 발전해오며 수정할 수 없다고 판단한 부분.

typeof null // object

instanceof

일종의 연산자이다. 객체의 프로토타입 체인을 검사한다. 아래의 경우를보면 타입을 잘 찾아주고 있다.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const p = {
  name: 'bonggu',
  age: 99
}

const bong = new Person('bonggu', 99);

bong instanceof Person; // true
p instanceof Person; // false

그러나 이러한 경우 문제가 발생하는데, 레퍼런스 타입이기 떄문에 최상위는 Object이다. 그래서 이러한 문제를 해결하기 위해 사용하는 것이 있다.

const arr = [];
const func = function() {}
const date = new Date();

arr instanceof Array; // true
date instanceof Date; // true
func instanceof Function; // true
//-------------------------------
arr instanceof Object; // true
date instanceof Object; // true
func instanceof Object; // true

대안

Object.prototype.toString.call('') // '[object String]'
Object.prototype.toString.call(arr) // '[object Array]'
Object.prototype.toString.call(func) // '[object Function]'

시사점

자바스크립트는 동적인 타입을 가진다. 그래서 타입검사가 어렵다.

typeof가 편하긴하지만 만능은아니다. 타입에 대한 검사를 하기 위한 방법을 찾는게 중요하다. 예를들어javascript is Function과 같은 검색어를 통해 잘 찾아보고 사용할 수밖에 없다.

상황에 잘 맞는 타입검사 방법을 찾아서 사용하는게 중요하다.

출처

profile
프론트엔드

0개의 댓글