JavaScript에서 프로토타입으로 속성 공유하는 방법
JavaScript에서는 객체의 prototype 속성에 값을 부착하여 여러 인스턴스가 동일한 속성을 공유하도록 만들 수 있습니다. 생성자 함수로 만든 모든 인스턴스는 프로토타입에 정의된 속성을 자동으로 상속받기 때문에, 공통 데이터를 반복해서 정의할 필요 없이 메모리를 효율적으로 사용할 수 있습니다.
예를 들어 학생(Student) 객체마다 이름과 나이는 다르지만, 소속 학교는 모두 같다면 school 속성을 프로토타입에 한 번만 정의하면 됩니다.
예제 코드
다음은 JavaScript에서 프로토타입을 사용해 속성을 공유하는 전체 코드입니다.
<!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 properties in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the view properties of student1 and student2 objects</h3>
<script>
let resEle = document.querySelector(".result");
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.school = "St Marks School";
let student1 = new Student("Rohan", 17);
let student2 = new Student("Shawn", 16);
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = `${student1.name} age ${student1.age} : school
:${student1.school} <br>`;
resEle.innerHTML += `${student2.name} age ${student2.age} : school
:${student2.school}`;
});
</script>
</body>
</html>코드 설명
Student 생성자 함수는 name과 age를 각 인스턴스의 고유 속성으로 설정합니다. 반면 Student.prototype.school = "St Marks School"; 구문은 프로토타입에 school 속성을 추가하므로, student1과 student2 두 객체가 이 값을 함께 공유하게 됩니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 나타납니다.

'CLICK HERE' 버튼을 클릭하면 두 학생 객체의 정보가 아래와 같이 출력됩니다.

출력 결과에서 볼 수 있듯이, 이름과 나이는 각 객체마다 다르게 표시되지만 school 값은 프로토타입에서 공유된 동일한 값("St Marks School")이 출력됩니다. 이처럼 프로토타입을 활용하면 공통 속성을 효율적으로 관리하고 코드 중복을 줄일 수 있습니다.