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

JavaScript에서 프로토타입 수정하는 방법

JavaScript 프로토타입 수정이란?

JavaScript에서 프로토타입(prototype)은 객체 간에 속성과 메서드를 공유할 수 있도록 해주는 핵심 메커니즘입니다. 생성자 함수의 prototype 객체에 정의된 메서드는 해당 생성자로 만들어진 모든 인스턴스에서 사용할 수 있으며, 프로그램 실행 중에도 언제든지 수정(재정의)할 수 있습니다.

아래 예제는 Person 생성자 함수의 프로토타입 메서드 displayInfo()를 정의한 뒤, 버튼을 클릭하는 시점에 같은 메서드를 새로운 로직으로 덮어써서 출력 형식이 어떻게 달라지는지 보여줍니다.

예제 코드

<!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: 20px;
        font-weight: 500;
        color: blueviolet;
    }
</style>
</head>
<body>
<h1>Modifying prototypes in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the original and modified prototype function</h3>
<script>
    let resEle = document.querySelector(".result");
    let BtnEle = document.querySelector(".Btn");
    function Person(name, age, occupation) {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }
    Person.prototype.displayInfo = function () {
        return `Name: ${this.name} Age: ${this.age} Occupation: ${this.occupation}<br>`;
    };
    let person1 = new Person("Shawn", 20, "student");
    let person2 = new Person("Rohan", 25, "Manager");
    BtnEle.addEventListener("click", () => {
        resEle.innerHTML =
        "Before Modifying prototype <br>" +
        person1.displayInfo() +person2.displayInfo();
        Person.prototype.displayInfo = function () {
            return `Occupation: ${this.occupation} Age: ${this.age} Name: ${this.name} <br> `;
        };
        resEle.innerHTML +="<br>After Modifying prototype <br>" +
        person1.displayInfo() +person2.displayInfo();
    });
</script>
</body>
</html>

실행 결과

JavaScript에서 프로토타입 수정하는 방법

'CLICK HERE' 버튼을 클릭하면 아래와 같이 기존 프로토타입 함수와 수정된 프로토타입 함수의 출력 결과를 화면에서 바로 비교해 볼 수 있습니다.

JavaScript에서 프로토타입 수정하는 방법

동작 원리 정리

  • 처음 정의된 Person.prototype.displayInfo는 이름 → 나이 → 직업 순으로 정보를 반환합니다.
  • 버튼을 클릭하면 먼저 기존 메서드의 결과가 화면에 표시됩니다.
  • 이후 같은 메서드가 직업 → 나이 → 이름 순으로 정보를 반환하는 새로운 함수로 재정의됩니다.
  • 프로토타입은 모든 인스턴스가 참조를 공유하기 때문에, 이미 생성된 person1과 person2 객체도 별도의 수정 없이 즉시 변경된 메서드를 사용하게 됩니다.