배워서 남 주자

디자인 패턴 - Prototype 패턴

미래에서 온 개발자 2023. 10. 11. 21:47

2. Prototype Pattern

Prototype 패턴

  • 동일한 타입의 여러 객체들이 프로퍼티를 공유할 때 유용하게 사용할 수 있다.
  • 생성자의 prototype 프로퍼티와 생성된 인스턴스의 __proto__ 프로퍼티는 동일하며, 이들을 통해 Prototype 객체를 확인할 수 있다.
class Dog {
  constructor(name) {
    this.name = name
  }

  bark() {
    return `Woof!`
  }
}

const dog1 = new Dog('Daisy')
const dog2 = new Dog('Max')
const dog3 = new Dog('Spot')

console.log(Dog.prototype)
// constructor: ƒ Dog(name, breed) bark: ƒ bark()

console.log(dog1.__proto__)
// constructor: ƒ Dog(name, breed) bark: ƒ bark()

console.log(Dog.prototype === dog1.__proto__) // true
  • 현재 객체에 없는 프로퍼티에 접근하려 하는 경우 JavaScript는 같은 이름의 프로퍼티를 찾을때까지 재귀적으로 객체의 proto 를 따라 거슬러 올라가게 된다.
  • Prototype 패턴은 어떤 객체가 다른 객체의 프로퍼티를 상속받을 수 있도록 해 준다.
  • Prototype 체인을 통해 해당 객체에 프로퍼티가 직접 선언되어 있지 않아도 되므로 메서드 중복을 줄일 수 있고 이는 메모리 절약으로 이어진다.

 

 

참고: 

1) ES5 생성자 함수

function Dog(name) {
  this.name = name;

  this.bark = function() { return 'Woof!'; }
}

 

2) ES6 클래스 문법

class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() { return `Woof!`; }
}

 

📚 더 읽어보면 좋은 글

https://typeof-undefined.tistory.com/7

https://bttrthn-ystrdy.tistory.com/30