[TIL] Inheritance

정세비·2021년 5월 26일
0

JavaScript

목록 보기
16/16
post-thumbnail

Inheritance(상속)은 각 클래스가 동일한 properties를 가지고 있는 경우, 새로운 class를 생성하여 공동으로 작성된 properties를 담아주어, 작성 코드를 줄여주는 작업을 이야기한다.
이떄 상속은 각각 공동의 속성 및 메서드를 갖고 있는 클래스를 subclass 라고 부르며,
이를 한 곳에 담아 모아둔 것을 Super class라고 한다. 각 subclass들은 super class의 속성과 메서드를 상속한다.

📌 property 상속

class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
 
  get name() {
    return this._name;
  }
 
  get behavior() {
    return this._behavior;
  }
 
  incrementBehavior() {
    this._behavior++;
  }
}

class Cat {
  constructor(name, usesLitter) {
    this._name = name;
    this._usesLitter = usesLitter;
    this._behavior = 0;
  }
 
  get name() {
    return this._name;
  }
 
  get usesLitter() {
    return this._usesLitter;
  }
 
  get behavior() {
    return this._behavior;
  }  
 
  incrementBehavior() {
    this._behavior++;
  }
}

👉 위에서 Dog class와 Cat class에서 동일 properites로 name 과 behavior, incrementBehavior()메서드가 사용되었다. 이를 super class인 Animal class로 묶어주면

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
 
  get name() {
    return this._name;
  }
 
  get behavior() {
    return this._behavior;
  }   
 
  incrementBehavior() {
    this._behavior++;
  }
} 

가 되어 아래와 같이 정리가 된다

확장해보기 (extends, super)

Super class인 Animal을 sub class인 cat으로 확장해보자

class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}
  • Animal class를 확장하는 새로운 Cat class를 만들어준다.
  • 이 때 extends 키워드는 Cat class 내에서 Animal class의 메서드를 사용할 수 있도록 확장해준다.
  • 새로운 Cat 객체를 만들 때 호출되는 constructornameusesLitter라는 두 개의 인수를 받는다.
  • super 키워드는 super class의 constructor를 호출한다. 이 경우, super(name)은 Cat class의 name 인수를 Animal class의 constructor로 전달한다.
  • Animal constructor가 실행되면 새로운 Cat 인스턴스에 대해 this._name = name;가 설정된다.
  • _usesLitter는 Cat class에만 있는 속성이므로 Cat constructor에서 설정해준다.

여기서 주의할 점은 constructor() 다음에 super을 호출한 후 usesLitter 속성을 설정해야한다는 것이다.
this키워드를 사용하기 전에 항상 super를 먼저 호출해야한다.

정세비 파주

적용해보기

const bryceCat = new Cat('Bryce', false); 
console.log(bryceCat._name); // output: Bryce

위의 작업이 끝난 후, bryceCat이라는 Cat class의 새 인스턴스를 만든 후 name과 usesLitter에 각자 'Bryce'와 false값을 넣어 호출해서 결과를 확인할 수 있다.



📌 methods 상속

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
 
  get name() {
    return this._name;
  }
 
  get behavior() {
    return this._behavior;
  }
 
  incrementBehavior() {
    this._behavior++;
  }
} 
 
 
class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}
 
const bryceCat = new Cat('Bryce', false);
console.log(bryceCat.name);

bryceCat.incrementBehavior(); // Call .incrementBehavior() on Cat instance 
console.log(bryceCat.behavior); // Log value saved to behavior

extends 는 super class의 모든 getter와 method를 sub class로 가져오므로 bryceCat.name은 getter에 접근하여 name property에 저장된 값을 return한다.

그렇다면 behavior는 무엇을 log할까? 정답은 1이다.

Cat class는 Animal class에서 _behavior property, behavior getter, .incrementBehavior() method를 상속한다.
따라서 bryceCat 인스턴스를 만들 때 Animal constructor는 _behavior property를 0으로 받는다.
그 후 .incrementBehavior()이 호출된 후 console.log를 하였기에 값이 1이 출력된다.



📌 sub class 자체

상속된 기능 외에 sub class 자체에도 property, getter, setter, method를 생성할 수 있다.

class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
 
  get usesLitter() {
    return this._usesLitter;
  }
}

위와 같이 Cat class에 _usesLitter에 저장된 값을 반환하는 usesLitter getter를 만들 수 있다.



📌 static methods

static method는 개별 instance에는 호출할 수 없고 오직 class에서만 호출할 수 있는 method이다.

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
 
  static generateName() {
    const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara'];
    const randomNumber = Math.floor(Math.random()*5);
    return names[randomNumber];
  }
} 

console.log(Animal.generateName()); // returns a name

const tyson = new Animal('Tyson'); 
tyson.generateName(); // TypeError

static을 이용해서 정적 메서드인 generateName()를 만들었다.
static 키워드로 인해 Animal class에서만 generateName()을 접근할 수 있으며
Animal class의 인스턴스나 하위 클래스의 인스턴스에서는 접근할 수 없다.

profile
파주

0개의 댓글