[javascript] 프로토타입의 다양한 사용 예시

프로토타입(prototype)은 자바스크립트의 핵심 개념 중 하나로, 객체 지향 프로그래밍 방식에 중요한 역할을 합니다. 프로토타입을 다양하게 활용하여 코드를 더 효율적으로 작성하고 재사용성을 높일 수 있습니다. 이번 글에서는 프로토타입의 활용 예시를 살펴보겠습니다.

1. 객체 생성자의 프로토타입 활용

프로토타입을 활용하여 공통 메서드를 한 번만 정의하고 모든 인스턴스에서 공유하여 사용할 수 있습니다. 아래는 객체 생성자와 프로토타입을 사용한 예시입니다.

// 객체 생성자
function Animal(name) {
  this.name = name;
}

// 프로토타입 활용
Animal.prototype.speak = function() {
  console.log(this.name + ' makes a noise');
}

let cat = new Animal('Kitty');
let dog = new Animal('Doggy');

cat.speak(); // 출력: Kitty makes a noise
dog.speak(); // 출력: Doggy makes a noise

이렇게 하면 speak 메서드를 모든 Animal 인스턴스에서 공유하여 사용할 수 있게 됩니다.

2. 기존 객체에 메서드 추가

프로토타입을 활용하여 기존 객체에 새로운 메서드를 추가할 수 있습니다. 아래는 Array 객체에 프로토타입을 사용하여 shuffle 메서드를 추가하는 예시입니다.

// Array 프로토타입에 shuffle 메서드 추가
Array.prototype.shuffle = function() {
  for (let i = this.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [this[i], this[j]] = [this[j], this[i]];
  }
  return this;
}

let arr = [1, 2, 3, 4, 5];
arr.shuffle();
console.log(arr); // 출력: [3, 2, 5, 1, 4] (랜덤한 순서로 섞인 배열)

3. 프로토타입 체이닝

프로토타입 체이닝을 활용하여, 객체 간 메서드 공유가 가능합니다. 아래는 프로토타입 체이닝을 사용하여 한 객체에서 다른 객체의 메서드를 호출하는 예시입니다.

// 부모 객체 생성자
function Parent(name) {
  this.name = name;
}

// 프로토타입 메서드 추가
Parent.prototype.sayHello = function() {
  return "Hello, " + this.name;
}

// 자식 객체 생성자
function Child(name) {
  Parent.call(this, name);
}

// 프로토타입 체이닝
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

let child = new Child('Alice');
console.log(child.sayHello()); // 출력: Hello, Alice

프로토타입을 활용하여 객체지향적인 코드를 더욱 유연하고 강력하게 작성할 수 있습니다.

프로토타입을 다양하게 활용하여 코드를 더 효율적으로 작성하고 재사용성을 높일 수 있습니다. 이를 통해, 객체 지향 프로그래밍에 있어서 자바스크립트의 강점을 최대한 활용할 수 있습니다.

참고 문헌