codecademy_Learn JavaScript (9) Classes

lilyoh·2020년 7월 27일
0

Introduction to Classes

class 는 비슷한 object 를 빠르게 만들기 위한 tool
class 를 이용하면 중복된 코드를 없애고 디버깅하는 시간을 줄일 수 있다

Constructor

객체와 클래스를 구분하는 가장 중요한 메소드 : constructor
자바스크립트에서, 클래스에 새로운 인스턴스를 생성할 때 무조건 constructor method 를 부른다

class Dog {
  constructor(name) {
    this.name = name;
    this.behavior = 0;
  }
}

Instance

An instance is an object that contains the property names and methods of a class, but with unique property values
인스턴스 = 객체
인스턴스는 프로퍼티 이름과 메소드를 가지고 있다
유일한 프로퍼티 값을 가지고 있다

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

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

Methods

클래스 메서드와 getter 구문은 객체의 메서드, getter 구문과 같다.
유일한 다른 점은 메서드 사이에 , 콤마를 붙이지 않는다는 것이다.

class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
  // 여기에 , 콤마가 없다
  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }
  
  incrementBehavior() {
    this._behavior++;
  }
}

Method Calls

메서드와 getter 를 불러오려면
인스턴스.메서드() 혹은 인스턴스.getter 하면 된다.

// calling getter
console.log(surgeon.name);
// calling method
surjeonCurry.takeVacationDays(3);

Inheritance

  • 코드 작성을 줄이기 위해서 공통 프로퍼티와 메서드를 가진 부모 클래스를 만들어 자식 클래스가 부모 클래스를 상속하게 할 수 있다.
  • 부모 클래스를 만들고 나면 다음과 같이 자식 클래스를 만들 수 있다.
class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}
  1. extends 키워드로 cat 클래스가 animal 클래스를 상속하겠다는 의미가 된다.
  2. super 키워드로 부모 클래스의 constructor 을 불러온다. super(name) 은 cat 클래스의 name 을 animal 클래스의 constructor 로 전달한다. animal 클래스가 작동하면 this._name = name; 이 실행되어 새로운 cat 인스턴스가 생성된다.
  3. _usesLitter 는 cat 클래스의 고유한 프로퍼티이기 때문에 cat constructor 에 생성한다.
  • 기억해야 할 것: constructor 에서 super 을 먼저 호출하고 난 뒤에 usesLitter 프로퍼티를 생성했다는 것을 기억하자. 항상 this 키워드를 먼저 사용해야 한다. 아니면 reference error 가 생길 것이다.

Static Methods

인스턴스에 상관없이 부모 클래스에서 직접 받아서 쓸 수 있는 메서드를 만들고 싶다면 static method 를 생성하면 된다.

static generatePassword() {
    return Math.floor(Math.random() * 10000);
  }

0개의 댓글