typeof와 instanceof 이해하기 | Javascript | 내장 객체

고광필·2022년 10월 4일
2

Front

목록 보기
27/33

최근 면접 본 회사에서 나온 질문이 있었습니다

class A {}

console.log(typeof A);
console.log(typeof new A());

위 코드의 결과가 무엇인가?를 묻는 질문이었는데
해당 질문을 통해서 typeof를 제대로 이해하지 못하고 있다는 생각이 들어 공부했고, 함께 언급되는 instanceof와 비교해서 글을 작성합니다

typeof

typeof는 변수나 값의 자료형을 문자열로 반환받을 수 있습니다

const num = 3;
console.log(typeof num); // 'number'

const string = 'feel';
console.log(typeof string); // 'string'

const testFunction = () => {}
console.log(typeof testFunction); // 'function'

const bool = false;
console.log(typeof bool); // 'boolean'

console.log(typeof undefined) // 'undefined'

number, string, function 등 자료형을 문자열로 반환받습니다

Null

const test = null;
console.log(typeof test); // 'object'

undefined의 자료형이 undefined이기 때문에, nulld의 자료형도 null로 예상할 수 있습니다
하지만 실제로 null의 경우 typeof 자료형은 object입니다
이는 자바스크립트 초기 개발시에 생긴 버그로 알려졌습니다

instanceof

instanceof는 변수나 값이 특정 객체의 인스턴스인지 유무를 boolean으로 반환합니다
다르게 표현하면 특정 객체로부터 만들어진건지 확인합니다

class Human {
    constructor(name) {
        this.name = name;
    }
}

const man = new Human('name');
console.log(man instanceof Human)

위 코드에서 변수 man은 클래스 Human을 통해 만들어졌습니다
따라서 man이 Human의 인스턴스인지 (man이 Human을 통해 만들어졌는지) 유무를 반환합니다

이걸 또 다르게 말하면 constructor를 비교한다고 할 수 있습니다
man의 constructor가 Human과 동일하다는걸 알 수 있습니다

instanceof가 주로 사용되는 경우는 class나 생성자함수 같은 커스텀 객체와 내장 객체로부터 만들어진건지 확인할 때 사용합니다

내장 객체

자바스크립트에서 미리 정의되어 내장된 객체를 의미합니다
대표적으로 Object, Date, Array 등이 있습니다

String과 Number 객체를 보면 알 수 있듯이 typeof는 object입니다
내장 String 객체, Number 객체이기 때문입니다

다시 첫 질문으로

최초에 궁금했던 내용은 class A의 자료형이 왜 function인지
생성한 변수는 왜 object인지 궁금했습니다

class의 경우 ES6에 추가되었는데, 기존에 있던 생성자 함수와 돌아가는 개념이 같습니다
따라서 class 문법 자체는 생성자 함수기 때문에 자료형이 function이 됩니다

class를 통해 생성한 값은 객체기 때문에 object가 됩니다

또한 class로부터 생성되었기 때문에 instanceof의 값이 true가 됩니다

참고

mdn docs - typeof
stackoverflow - javascript: what's the difference between a function and a class
Why in JavaScript class A instanceof Function, but typeof class A is not an object?

profile
이해하는 개발자를 희망하는 고광필입니다.

0개의 댓글