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

JavaScript에서 배열 내 여러 객체가 하나의 메서드를 공유하는 방법

배열 내 객체 간 메서드 공유하기

JavaScript에서 여러 객체가 동일한 메서드를 사용하도록 만들고 싶다면 프로토타입(prototype)을 활용하는 것이 가장 효율적입니다. 생성자 함수의 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: 18px;
        font-weight: 500;
        color: rebeccapurple;
    }
</style>
</head>
<body>
<h1>Share a method between objects in an array</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call welcome() method of all person objects</h3>
<script>
    let resEle = document.querySelector(".result");
    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    Person.prototype.welcome = function () {
        return "Welcome " + this.firstName + " " + this.lastName;
    };
    let obj = [
        new Person("Rohit", "Sharma"),
        new Person("Shawn", "Mendes"),
        new Person("Michael", "Clarke"),
    ];
    document.querySelector(".Btn").addEventListener("click", () => {
        obj.forEach((item) => {
            resEle.innerHTML += item.welcome() + "";
        });
    });
</script>
</body>
</html>

출력 결과

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

JavaScript에서 배열 내 여러 객체가 하나의 메서드를 공유하는 방법

'CLICK HERE' 버튼을 클릭하면 −

JavaScript에서 배열 내 여러 객체가 하나의 메서드를 공유하는 방법

핵심 포인트

  • Person.prototype.welcome처럼 생성자 함수의 prototype에 메서드를 추가하면, 모든 인스턴스가 같은 메서드를 공유합니다.
  • 각 객체마다 메서드를 개별적으로 정의하는 것과 달리, 프로토타입 방식은 메모리를 절약하고 유지보수가 쉽습니다.
  • forEach()를 사용해 배열 내 모든 객체의 공유 메서드를 손쉽게 호출할 수 있습니다.