Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 객체가 클래스의 인스턴스인지 확인하는 방법

JavaScript에서 어떤 객체가 특정 클래스의 인스턴스인지 확인해야 하는 경우가 자주 있습니다. 이럴 때 instanceof 연산자를 사용하면 간단하게 확인할 수 있습니다.

instanceof 연산자란?

instanceof 연산자는 객체가 특정 생성자 함수나 클래스로 생성된 인스턴스인지 검사하고, 그 결과를 불리언 값(true 또는 false)으로 반환합니다. 상속 관계가 있는 경우에도 프로토타입 체인을 따라 올라가며 검사하기 때문에 부모 클래스의 인스턴스 여부도 정확하게 판별할 수 있습니다.

예제

다음은 Student 클래스의 인스턴스인지 확인하는 전체 코드입니다.

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
    body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    .result {
        font-size: 20px;
        font-weight: 500;
        color: blueviolet;
    }
</style>
</head>
<body>
<h1>객체가 클래스의 인스턴스인지 확인하기</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>위의 버튼을 클릭하면 student1 객체가 Student의 인스턴스인지 확인합니다</h3>
<script>
    let resEle = document.querySelector(".result");
    function Student(name, age, standard) {
        this.name = name;
        this.age = age;
        this.standard = standard;
    }
    let student1 = new Student("Rohan", 18, 12);
    document.querySelector(".Btn").addEventListener("click", () => {
        if (student1 instanceof Student) {
            resEle.innerHTML = "student1은 Student의 인스턴스입니다";
        } else {
            resEle.innerHTML = "student1은 Student의 인스턴스가 아닙니다";
        }
    });
</script>
</body>
</html>

코드 설명

  • Student 생성자 함수를 정의하고, new 키워드를 사용해 student1 객체를 생성합니다.
  • 버튼을 클릭하면 if (student1 instanceof Student) 조건문을 통해 해당 객체가 Student의 인스턴스인지 검사합니다.
  • 검사 결과에 따라 화면에 적절한 메시지가 출력됩니다.

출력

JavaScript에서 객체가 클래스의 인스턴스인지 확인하는 방법

'CLICK HERE' 버튼을 클릭하면 아래와 같이 검사 결과가 화면에 표시됩니다.

JavaScript에서 객체가 클래스의 인스턴스인지 확인하는 방법

마무리

이처럼 instanceof 연산자를 활용하면 객체의 타입을 손쉽게 검증할 수 있어, 타입 체크가 필요한 유효성 검사나 조건 분기 로직을 작성할 때 매우 유용합니다.