[TIL][OOP(object-oriented programming)] Instantiation Patterns

김태수·2020년 10월 28일
0
post-thumbnail

바로 이전 객체지향 포스트에서 간략하게 ES6 이전의 인스턴스 생성 방법과, ES6 이후의 인스턴스 생성 방법을 소개하였다. 가장 큰 차이는 function 사용과 class 사용 일것이다.
해당 코드를 살펴보며 Instantiation Pattern 즉 인스턴스를 만드는 과정에 대해 알아보려 한다.

ES5 까지의 인스턴스 생성은

class 대신 함수를 이용하여 인스턴스를 생성한다.
그 생성 방식은 크게 네가지 방식이 있는데

  • Functional Instantiation
  • Functional Shared
  • Prototypal Instantiation
  • Pseudoclassical

이중 현재까지도 많이 쓰이는 Pseudoclassical 에 대해 좀 더 자세히 알아보았다!

Pseudoclassical
.
.

  • ES6의 class 역할을 수행할 함수 필요.
  • this 키워드 사용하여 함수 안에 instance에 상속될 속성 정의
  • prototype 을 사용하여 instance에 상속될 메소드 정의
  • 새로운 인스턴스 생성은 new 키워드를 사용하여 생성
    .
    .
function Members(name, sex, age, height, weight, membership) {
	this.name = name;
        this.sex = sex;
        this.age = age;
        this.height = height;
        this.weight = weight;
        this.membership = membership;
}
.
.
// method 정의___________________________________
Members.prototype.addMonth = function() {
	this.membership += 30;
    	console.log(`${this.membership} days left`);
}
Members.prototype.sayHello = function() {
    	console.log(`${this.name}님 안녕하세요! 회원권은 ${this.membership}일 남았습니다!`);
}
.
.
// 새 instance 생성______________________________
let 김태수 = new Members('김태수', 'male', 25, 183, 68, 90);
.
.
.
.
.
김태수.sayHello() ===> '김태수님 안녕하세요! 회원권은 90일 남았습니다!'

현재는 class 와 constructer 를 사용한 객체지향 프로그래밍 방식이 일반적이지만 레거시코드, 또는 다른 어떠한 이유들로 인해 이전 방식인 function을 이용한 pseudoclassical 방법 또한 많이 이용되고 있다. 지금까지는 최신 문법들로만 공부하는게 최고라고 여겼지만, 최신 문법이라 해서 해당 방법만 알고있는게 아닌, 기존 서비스의 유지보수를 위해서 이전세대 방법 또한 익혀두는것 또한 중요하다고 생각되었다!

profile
개발학습 일기

0개의 댓글