개발/javascript

[클린코드 자바스크립트] 타입검사

cookveloper 2022. 3. 7. 20:37

 

* 클린코드 자바스크립트 강의를 정리하고자 작성한 게시글입니다.

타입검사

  • 반환되는 값은 문자열이다.
  • 원시형 데이터는 typeof로 수월한 검사가 가능하지만 참조형의 경우 정확한 검사가 이루어지기는 어렵다.
  • typeof, instanceof, Object.prototype.toString.call(검사하고자 하는 값) 으로 타입을 검사할 수 있다.
  • instanceof: 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별한다. 
function testFunction() {}
class TestClass {}

const str = new String('문자열');

typeof '문자열' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof 12 // 'number'
typeof Symbol() // 'symbol'
typeof testFunction // 'function'
typeof TestClass // 'function'
typeof str // 'object'
typeof null // 'object'
function Person(name, age) {
    this.name = name;
    this.age = age;
}
const p = {
   name: 'kim',
   age: 11
}

const kim = new Person('kim', 11);

kim instanceof Person // true

p instanceof Person // false
const arr = [];
const func = function() {}
const date = new Date();

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

# 레퍼런스 객체의 최상위는 object 이기 때문에 true
arr instanceof Object  // true
func instanceof Object  // true
date instanceof Object  // true 
Object.prototype.toString.call('')  // '[object String]'
Object.prototype.toString.call(arr)  // '[object Array]'
Object.prototype.toString.call(func)  // '[object Function]'
반응형