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

JavaScript 상속 완벽 이해하기: 프로토타입 기반 상속 예제

JavaScript는 프로토타입(prototype) 기반의 객체 지향 언어입니다. Java나 C++ 같은 클래스 기반 언어와 달리, JavaScript에서는 prototype 객체를 활용하여 상속을 구현합니다.

프로토타입 상속의 기본 개념

생성자 함수로 객체를 생성하면, 해당 객체는 생성자 함수의 prototype 속성에 정의된 메서드와 속성을 그대로 물려받습니다. 즉, 여러 객체가 동일한 메서드를 공유할 수 있어 메모리를 효율적으로 사용할 수 있습니다.

JavaScript 상속 구현 예제

다음은 생성자 함수와 prototype 객체를 사용하여 상속을 구현하는 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<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: 18;
        color: blueviolet;
        font-weight: 500;
    }
</style>
</head>
<body>
<h1>JavaScript Inheritance</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to call the welcome method inherited by person1 and person2 object
</h3>
<script>
    let BtnEle = document.querySelector(".Btn");
    let resEle = document.querySelector(".result");
    function Person(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    Person.prototype.welcome = function () {
        resEle.innerHTML +=
        " Welcome "+this.name+" age: "+this.age +" city: "+this.city+"<br>";
    };
    BtnEle.addEventListener("click", () => {
        let person1 = new Person("Rohan", 22, "Delhi");
        person1.welcome();
        let person2 = new Person("Shawn", 19, "England");
        person2.welcome();
    });
</script>
</body>
</html>

코드 설명

  • Person 생성자 함수: 이름(name), 나이(age), 도시(city)를 매개변수로 받아 각 객체의 고유 속성으로 설정합니다.
  • prototype.welcome 메서드: Person.prototypewelcome() 메서드를 추가하면, new Person()으로 생성된 모든 객체가 이 메서드를 상속받아 사용할 수 있습니다.
  • 객체 생성 및 호출: 버튼을 클릭하면 person1과 person2 객체가 생성되고, 두 객체 모두 상속받은 welcome() 메서드를 호출합니다.

실행 결과

코드를 실행하면 다음과 같은 초기 화면이 나타납니다.

JavaScript 상속 완벽 이해하기: 프로토타입 기반 상속 예제

'CLICK HERE' 버튼을 클릭하면, person1과 person2 객체가 상속받은 welcome() 메서드가 실행되어 아래와 같이 각 객체의 정보가 출력됩니다.

JavaScript 상속 완벽 이해하기: 프로토타입 기반 상속 예제

이처럼 JavaScript에서는 prototype 객체를 통해 속성과 메서드를 여러 객체가 공유하는 형태의 상속을 손쉽게 구현할 수 있습니다.