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

JavaScript에서 프로토타입(Prototype)으로 메소드 공유하기

JavaScript에서 메소드를 여러 객체가 함께 사용하도록 만들고 싶다면, 객체의 prototype 속성에 메소드를 연결하면 됩니다. 이렇게 정의된 메소드는 해당 생성자 함수로 생성된 모든 인스턴스가 공유하게 됩니다.

prototype에 메소드를 등록하면 인스턴스마다 메소드가 복사되지 않고 하나의 메소드를 참조하기 때문에, 메모리 사용 측면에서도 효율적이라는 장점이 있습니다.

JavaScript에서 메소드를 공유하는 예제 코드

아래 코드에서는 Student 생성자 함수의 prototype에 displayInfo 메소드를 추가하여, 두 개의 학생 객체(student1, student2)가 동일한 메소드를 공유하도록 구현했습니다.

예제

<!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>Shared methods in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the call the displayInfo method of student1 and student2 object</h3>
<script>
   let resEle = document.querySelector(".result");
   function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
   }
   Student.prototype.displayInfo = function () {
      return `${this.name} age ${this.age} : standard :${this.standard} <br>`;
   };
   let student1 = new Student("Rohan", 17, 12);
   let student2 = new Student("Shawn", 16, 11);
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = student1.displayInfo();
      resEle.innerHTML += student2.displayInfo();
   });
</script>
</body>
</html>

실행 결과

페이지를 처음 열었을 때의 초기 화면은 아래와 같습니다.

JavaScript에서 프로토타입(Prototype)으로 메소드 공유하기

여기서 'CLICK HERE' 버튼을 클릭하면, student1과 student2 객체 각각에 대해 displayInfo() 메소드가 호출됩니다. 두 객체는 서로 다른 인스턴스지만 같은 prototype 메소드를 공유하고 있으므로, 아래와 같이 각 학생의 이름, 나이, 학년 정보가 화면에 출력됩니다.

JavaScript에서 프로토타입(Prototype)으로 메소드 공유하기

정리

이처럼 prototype 속성을 활용하면 하나의 메소드를 여러 인스턴스가 재사용할 수 있어, 코드 중복을 줄이고 메모리 효율성까지 높일 수 있습니다. 동일한 동작을 하는 메소드를 여러 객체에 적용해야 한다면 prototype 활용을 적극적으로 고려해 보세요.