instanceof 연산자는 생성자 함수의 prototype 속성이 특정 객체의 프로토타입 체인 어딘가에 존재하는지 검사합니다. 좀 더 쉽게 표현하면, 어떤 변수가 특정 타입에 속하는지 확인하는 연산자라고 할 수 있습니다. 다만 사용 시 몇 가지 주의해야 할 사항이 있으므로, 예제를 통해 하나씩 살펴보겠습니다.
원시 타입(Primitive)에서의 동작
문자열과 숫자는 원시 값(primitive value)으로, 객체가 아니기 때문에 내부 슬롯인 [[Prototype]]을 갖지 않습니다. 따라서 instanceof는 이들을 일반 객체(Number, String 래퍼 객체)로 감쌌을 때만 올바르게 작동합니다.
예제
console.log(1 instanceof Number)
console.log(new Number(1) instanceof Number)
console.log("" instanceof String)
console.log(new String("") instanceof String)
출력 결과
false true false true
위 결과에서 알 수 있듯이, 리터럴 형태의 숫자나 문자열은 false를 반환하지만, new 키워드로 생성한 래퍼 객체는 true를 반환합니다.
생성자 함수(Constructor) 검사
객체를 반환하는 생성자 함수나 자바스크립트 클래스로 만든 인스턴스는 instanceof 연산자를 사용해 손쉽게 타입을 확인할 수 있습니다.
예제
function Person(name) {
this.name = name
}
let john = new Person("John");
console.log(john instanceof Person)
출력 결과
true
상속 관계에서의 동작
자바스크립트는 프로토타입 기반 상속을 지원합니다. 따라서 상속 계층 구조에 있는 어떤 클래스로 instanceof를 검사하더라도 모두 true가 반환됩니다.
예제
class Person {}
class Student extends Person {
constructor(name) {
super()
this.name = name
}
}
let john = new Student("John");
console.log(john instanceof Person)
console.log(john instanceof Student)
출력 결과
true true
john은 Student의 인스턴스이면서 동시에 부모 클래스인 Person의 인스턴스이기도 합니다. 이처럼 instanceof는 프로토타입 체인 전체를 거슬러 올라가며 검사하기 때문에, 상속 관계에 있는 모든 클래스에 대해 true를 반환합니다.