자바스크립트는 생성자 함수와 new 연산자를 통해 인스턴스를 생성할 수 있다.
function Person(lastName) {
this.lastName = lastName
this.setLastName = function (name) {
this.lastName = lastName;
}
this.getLastName = function () {
return this.lastName
}
}
const me = new Person("Lee")
console.log(me.getLastName()) // Lee
console.log(me.setLastName("Kim"))
위의 결과는 생성자 함수로 객체를 생성하는 예시이며 정상 동작한다. 하지만 아래와 같이 여러개의 인스턴스를 생성할시 문제가 생긴다.
const me = new Person("Lee")
const you = new Person("Kim")
const her = new Person("Go")
각각의 인스턴스들이 같은 로직의 메소드를 소유하고 있다. 이는 메모리 낭비를 야기한다.
Person.prototype.setName = function(lastName) {
this.lastName = lastName
}
Person.prototype.getName = function() {
return this.name
}
console.log(me.getName()) // Lee
Person 생성자 함수의 prototype 프로퍼티가 가리키는 프로토타입 객체로 이동시킨 메소드는 프로토타입 체인에 의해 모든 인스턴스가 참조할 수 있다. 프로토타입 객체는 상속할 것들이 저장되는 장소이다.
의사 클래스 패턴 상속
의사 클래스 패턴은 자식 생성자 함수의 prototype 프로퍼티를 부모 생성자 함수의 인스턴스로 교체하여 상속을 구현하는 방법이다.
const Parent = (function () {
function Parent(lastName) {
this.lastName = lastName
}
Parent.prototype.sayHi = function () {
console.log(`hi ${this.lastName}`)
}
return Parent
})()
const Child (function () {
function Child(lastName) {
Parent.apply(this, arguments)
}
Child.prototype = new Parent()
Child.prototype.sayHi = function () {
console.log(`hello ${this.lastName}`)
}
Child.prototype.sayBye = function () {
console.log(`bye ${this.lastName}`)
}
위 코드를 도식화 하면 아래와 같다.
의사 클래스 패턴은 구동상의 문제는 없지만 몇가지 문제가 있다.
프로토타입 패턴 상속은 Object.create 함수를 사용하여 객체에서 다른 객체로 직접 상속을 구현하는 방식이다.
Object.create() 메서드는 지정된 프로토타입 객체 및 속성(property)을 갖는 새 객체를 만든다.
const Parent = (function () {
function Parent(lastName) {
this.lastName = lastName
}
Parent.prototype.sayHi = function () {
console.log(`hi ${this.lastName}`)
}
return Parent
})()
const Child = (function () {
function Child(lastName) {
Parent.apply(this, arguments)
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
return Child
})()
위 코드를 도식화 해보면 아래와 같다.