프로토타입과 객체지향

이재윤·2021년 4월 28일
0

JavaScript

목록 보기
2/10
post-thumbnail

💻 생성자 함수와 인스턴스의 생성

자바스크립트는 생성자 함수와 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 프로퍼티가 가리키는 프로토타입 객체로 이동시킨 메소드는 프로토타입 체인에 의해 모든 인스턴스가 참조할 수 있다. 프로토타입 객체는 상속할 것들이 저장되는 장소이다.

💻 상속

  1. 의사 클래스 패턴 상속

    의사 클래스 패턴은 자식 생성자 함수의 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}`)
  }

위 코드를 도식화 하면 아래와 같다.
의사 클래스 패턴은 구동상의 문제는 없지만 몇가지 문제가 있다.

  • new 연산자를 통해 인스턴스를 생성한다.
  • 생성자 링크의 파괴
    child의 프로토타입 객체는 Parent의 인스턴스이며 contructor 프로퍼티가 없다. 따라서 child의 constructor를 참조하게 되면, 프로토타입 체이닝에 의해 Person prototype 객체의 constructor를 참조하게 된다.
  • 객체리터럴로 객체를 생성하는 경우 위 방법이 불가능 하다.
  1. 프로토타입 패턴 상속

    프로토타입 패턴 상속은 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
})()

위 코드를 도식화 해보면 아래와 같다.

  1. Person.prototype을 프로토타입 객체로 갖는 객체를 생성한 후 Child 생성자 함수의 prototype 프로퍼티와 연결한다.
  2. Object.create 함수로 객체를 생성할 경우 [[Prototype]]을 제외하고 다른 프로퍼티는 가지고 있지 않다. 따라서 constructor 프로퍼티를 선언해 Child 생성자 함수를 가리키게 해야 한다.
참고자료 https://poiemaweb.com/js-object-oriented-programming

0개의 댓글