상세 컨텐츠

본문 제목

코드카데미 Javascript - 클래스와 인스턴스, 상속, 정적 메소드

IT/Javascript

by J KIMS 2020. 9. 27. 10:56

본문

반응형

 

 

Class 의 개념

 

자바스크립트는 객체 지향 언어 (OOP: Object - Oriented Programming language)이다.

객체를 통해 현실의 모델을 구현할 수 있다. 클래스는 비슷한 객체들을 빠르게 만들어내도록 도와준다.

 

클래스는 객체의 템플릿이다

 

클래스를 만들때는 class 라는 키워드를 사용하고 클래스 안에는 생성자(constructor)가 있다.

자바스크립트는 클래스의 새로운 인스턴스를 만들 때 생성자 메소드를 호출한다.

 

class Surgeon {
  constructor(name, department){
    this.name = name;
    this.department = department;
  }
}

클래스는 객체와 달리 {} 괄호 앞에 = 도 없고 비슷하지만 다르다.

 


Instance 인스턴스

 

인스턴스는 클래스의 속성과 메서드를 담고 있는 객체이다. 

클래스로 만든 객체가 인스턴스라고 생각하면 쉬움.

 

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');

 

위 코드에서 surgeonCurry와 surgeonDurant는 Surgeon의 인스턴스를 담고 있는 변수들이다.

변수에 클래스를 저장할 때는 new 키워드를 사용한다.

 

 


클래스의 메소드

 

class Surgeon {
  constructor(name, department) {
    // Add underscore to each property
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }

  get name(){
    return this._name;
  }

  get department(){
    return this._department;
  }

  get remainingVacationDays(){
    return this._remainingVacationDays;
  }

  takeVacationDays(daysOff){
    this._remainingVacationDays = this._remainingVacationDays - daysOff;
  }

}

const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');

// Method Calls

console.log(surgeonCurry.name); //Curry

surgeonCurry.takeVacationDays(3);
console.log(surgeonCurry.remainingVacationDays); //17

 

getter 메소드를 생성하기 위해 원래 변수들의 이름앞에 언더스코어(_)를 붙였다.

 

💡 주의 : 클래스는 각 메소드들을 구분하기 위해 콤마가 필요하지 않다

 

메소드를 호출하는 방식은 보통 객체와 동일하다.

 


Inheritance 상속

 

부모 클래스(parent class)자식 클래스(child class)들의 공통된 속성과 메소드를 갖고있다.

 

상속을 이용하면 자식 클래스는 부모 클래스의 속성과 메소드를 물려받게 된다.

또, 부모 클래스에 없는 속성이나 메소드를 추가하는 것이 가능하다.

 

출처 : 코드카데미 Learn Javascript Class 강의 중

클래스를 상속할 때는 extendssuper가 필요하다.

- super는 부모의 생성자를 호출한다

- extends는 부모의 모든 메소드들을 자식 클래스로 가져옴

 

주의할 점은 생성자(constructor)안에 반드시 super를 먼저 써야한다. 그렇지 않으면 reference error가 발생한다.

 

class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

// Inheritance
class Nurse extends HospitalEmployee {
  constructor(name, certifications){
    super(name);
    this._certifications = certifications;
  }

  addCertification(){}
}

// Create new instance
const nurseOlynyk = new Nurse('Olynyk',['Trauma', 'Pediatrics']);

 

💡 상속의 장점

- 부모 클래스의 하위 클래스가 여럿 있을때, 부모 클래스만 수정해도 전체에 반영됨

- 상속을 쓰면 코드 크기도 줄어듬 

 


Static Methods 정적 메소드

 

정적 메소드는 부모 클래스에서 언제든지 직접 가져와서 쓸 수 있지만 각 인스턴스에서는 사용 불가능하다.

(= 인스턴스로 만든 객체에는 정적 메소드가 존재X)

 

정적 메소드는 메소드 앞에 static을 붙여서 만든다.

 

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

 

위에서 generateName이 정적 메소드이다. 오로지 직접 호출하는 것만 가능하다.

 

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

 

만약 위와같이 인스턴스로 접근을 시도하면 TypeError가 뜬다.

반응형

관련글 더보기

댓글 영역