2. Prototype Pattern
- 동일한 타입의 여러 객체들이 프로퍼티를 공유할 때 유용하게 사용할 수 있다.
- 생성자의 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!`; }
}
📚 더 읽어보면 좋은 글
'배워서 남 주자' 카테고리의 다른 글
디자인 패턴 - Provider 패턴 (0) | 2023.10.15 |
---|---|
디자인 패턴 - Factory 패턴 (0) | 2023.10.15 |
디자인 패턴 - Singleton 패턴 (0) | 2023.10.08 |
디자인 패턴 - introduction (1) | 2023.10.08 |
innerText, textContent, innerHTML의 차이 (0) | 2023.09.24 |