갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • 프로토타입
  • structure
  • 호이스팅
  • 객체타입
  • 상속
  • 심볼
  • 인터프리터
  • symbol
  • 함수
  • prototype
  • 정적 레벨
  • 이터러블
  • Babel
  • function
  • 컴파일러
  • 자바스크립트엔진
  • 네이밍
  • ECMAScript
  • 렉시컬 환경
  • 실행 컨텍스트
  • nodemon
  • SPREAD
  • this
  • 오버라이딩
  • 원시타입
  • class
  • Arrow
  • 스코프 체인
  • 싱글스레드
  • PM2

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

Study/JavaScript(Clean code)

[JavaScript][clean-code] 타입 검사

2022. 5. 26. 20:14

* 타입 검사에 대한 방법

  • typeof
  • instanceof
  • Object.prototype.toString.call('')

* typeof

- typeof연산자가 피연산자를 평가한뒤 문자열로 반환해준다.

 

ex) typeof 'Hello' // 'string'

 

* typeof의 문제점

  • primitive value는 대부분 typeof로 검사가 가능하나 reference value는 감별하기 어렵다.
  • typeof null 
    • 'object'가 반환된다.
    • 언어적인 오류이다. (수정할 수 없다고 판단되어 계속 사용되고 있음)
  • typeof는 만능이 아니다.

* instanceof (typeof와 유사)

- 생성자의 prototype속성이 객체의 prototype chain어딘가에 존재하는지 판별한다.

 

* instanceof 예시코드

function Person(name, age, year) {
  this.name = name;
  this.age = age;
}
const man = new Person('Hyeonwoo', 29);

console.log(man instanceof Person);
// expected output: true

console.log(man instanceof Object);
// expected output: true

 

* instanceof의 문제점

  • reference type이기 때문에 결국 최상위는 Object이다.
  • prototype chain으로 인해서 함수, 배열, 객체는 결국 최상위에 Object가 있다.
  • 이로인해 더더욱 type검사가 어렵고 헷갈린다.
const arr = [];
const func = function() {}
const date = new Date()

arr instanceof Array // true
func instanceof Function // true
date instanceof Date // true

arr instanceof Object // true
func instanceof Object // true
date instanceof Object // true

 

* object prototype chain을 타기 때문에 그걸 역이용한다.

  • reference type까지 감지 할 수 있다.
  • 완벽하진 않지만 이런식으로도 검사를 할 수 있다.
const func = function() {}

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

 

 

* 결론적으로

  • 항상 타입을 검사할때는 조심하자
  • 스택오버플로우를 이용하여 검색을 항상 활용하자
  • 검색 추천 키워드
    • javascript is function // javascript is array
  • 자바스크립트는 동적인 타입이여서 타입검사가 어렵다. 따라서 잘 찾아서 검사를 해야한다.

* primitive vs reference

- 값과 참조의 차이는 해당 링크 내용을 통해서 참조

https://latte1114.tistory.com/315

'Study > JavaScript(Clean code)' 카테고리의 다른 글

[JavaScript][clean-code] undefined & null  (0) 2022.05.27
[JavaScript][clean-code] eqeq줄이기 & 형 변환 주의하기  (0) 2022.05.27
[JavaScript][clean-code] 호이스팅 주의하기  (0) 2022.05.26
[JavaScript][clean-code] 임시변수를 제거하자  (0) 2022.05.26
[JavaScript][clean-code] 전역 변수 사용 최소화  (0) 2022.05.26
    'Study/JavaScript(Clean code)' 카테고리의 다른 글
    • [JavaScript][clean-code] undefined & null
    • [JavaScript][clean-code] eqeq줄이기 & 형 변환 주의하기
    • [JavaScript][clean-code] 호이스팅 주의하기
    • [JavaScript][clean-code] 임시변수를 제거하자
    갈푸라떼
    갈푸라떼

    티스토리툴바