JavaScript 객체 지향 - class

김민재·2021년 7월 10일
0
post-thumbnail

constroctor vs class

  • constroctor function
  1. 객체를 만든다.
  2. 객체의 초기상태를 세팅한다.

    -constroctor function은 사용될 때
    new 키워드를 붙이면 객체가 리턴된다.
    -객체가 리턴되기 전에 객체의 속성이 기본적으로 세팅된다.
    -그렇기에 new 키워드가 붙으면 Person 함수는 일반적인 함수가 아닌 생성자가 된다.

class

  • 클래스란 객체를 만드는 공장이다.
  • 자바스크립트의 클래스에서 생성자 함수를 구현하는 방법은 다음과 같다.
    -객체가 생성될 때 객체의 초기상태를 지정하기 위한 객체가 만들어지기 직전에 실행되어지도록 약속된 함수가 바로 constructor(){}이다.
  • class를 통해서 객체를 생성할 때 모든 객체가 공유하는 공통(prototype)의 객체를 생성하는 방법은 다음과 같다.
    -class 내부에 함수명(){}을 만들어주면 같은 class가 공유하고 있는 객체가 만들어진다.
    특정 객체 다르게 동작하는 메소드를 만드는 방법은 생성자함수에서와 동일하다.
<script>
class Person{
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;  
  }
  sum() {
    return 'prototype :' + (this.first+this.second+this.third);
  }  
}
const k = new Person('kim',10, 20, 30);
k.sum = function(){
  return 'this :' +  (this.first+this.second+this.third);
} 
const m = new Person('MIN',10, 10, 10);
console.log('k', k);
console.log('kim.sum()', k.sum())
</script>

inheritance, 상속

  • 상속이란 기존의 부모 class의 기능요소를 자식 class가 이어받아 공유하는 것을 의미한다.

    -자식 class는 부모의 기능요소 뿐만 아니라 새로운 기능을 추가하여 사용할 수 도 있다.
  • extends 키워드를 사용하여 기존에 가지고 있는 부모 class의 기능 요소들을 그대로 자식 class에 로딩, 즉 상속받을 수 있다.
    -상속을 사용하면 중복되는 코드를 제거하기에 코드의 양을 줄일 수 있다.
    -중복된 코드 수정시 그 코드를 상속받고 있는 모든 클래스에서 동시에 변경이 일어나기에 유지보수 편의성을 도모할 수 있다.
<script>
class Person{
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;  
  }
  sum() {
    return 'prototype :' + (this.first+this.second+this.third);
  }
}
class PersonPlus extends Person{
  avg() {
    return (this.first+this.second+this.third)/2;
  }
}
const k = new PersonPlus('kim',10, 20, 30);
console.log('k.sum()', k.sum());
console.log('k.avg()', k.avg());
</script>

super

  • 상속받은 자녀 class의 생성자에 property를 추가하고 싶을때 부모 class에서 상속받은 부분을 super()를 사용하여 추가하고 싶은 프로퍼티를 추가한다.
  • super()를 통해 부모 class의 constructor를 호출하여 부모 클래스 초기 셋팅값을 호출 할 수 있다.
  • super.메소드 명()을 통해 부모 class의 메소드를 호출하여 메소드에 해당 하는 리턴 값을 반환해준다.
    -부모 class에서 기능을 추가하고 싶을 때 필요한 코드를 자식 class에 중복 작성하는 것을 막아준다.
    -자식 class에서 부모 class의 속성 값에 접근할 수 있다.
<script>
class Person{
  constructor(name, first, second, third){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;  
  }
  sum() {
    return this.first+this.second+this.third;
  }
}
class PersonPlus extends Person{
  constructor(name, first, second, third, forth){
    super(name, first, second, third);
    this.forth = forth;
  }
  sum() {
    return super.sum()+this.forth;
  }
  avg() {
    return (this.first+this.second+this.third+this.forth)/4;
  }
}
const k = new PersonPlus('kim',10, 20, 30, 40);
console.log('k.sum()', k.sum());
console.log('k.avg()', k.avg());
</script>
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글