[TIL. 09] JavaScript- class

신지원·2021년 2월 25일
0

JavaScript

목록 보기
4/5
post-thumbnail

Class

동일한 종류의 객체를 여러개 생성해야 하는 경우 class 를 이용하면 간단해진다.
음.. 약간 템플릿이라고 생각해 볼 수 있다.

Constructor

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

클래스에 새로운 인스턴스를 만들때마다 constructor method 를 실행해주어야 한다.
Constructor는 객채의 기본 상태를 설명해준다.
클래스명은 항상 대문자로 시작해야한다.

Instance

class Dog {
  constructor(name) {
    this.name = name;
    this.behavior = 0;
  } 
}
 
const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name); // Log the name value saved to halley
// Output: 'Halley'

instance는 property들과 class의 method를 포함하는 객체이다. 그렇지만, 특정한 property의 값을 가진다.
instance를 만들때는 항상 new를 써주어야 한다.
위의 instance를 보면, constructor()를 실행시켜주고 그 안의 코드들을 실행시켰다.

Method

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

let nikko = new Dog('Nikko'); // Create dog named Nikko
nikko.incrementBehavior(); // Add 1 to nikko instance's behavior
let bradford = new Dog('Bradford'); // Create dog name Bradford
console.log(nikko.behavior); // Logs 1 to the console
console.log(bradford.behavior); // Logs 0 to the console

class안에 method를 실행하고, 불러 올 수 있다.
method 실행법은 객체에서 했던 방법이랑 똑같고, getter 와 setter의 작성법도 객체에서 했던거랑 똑같다.

class 상속

class 상속을 이용하면 부모 class 를 만들고 그 밑에 child class를 만들어 클래스를 다른 클래스로 확장할 수 있다.
property들과 method등이 상속된다(getter,setter도)

extend, super

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

이렇게 animal class 가 있고, 위의 사진처럼 cat class를 만들려고 한다.
근데 cat과 animal은 겹치는 property가 2개나 있고, method는 아예 똑같다.
이런 경우, animal 클래스에 상속을 받아 cat 클래스를 만들면 더욱 간단하다.

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

이런식으로 사용할 수 있다.

extends는 상속받을 class와 같이 온다. cat 클래스 안에서 animal 클래스의 method 를 사용할 수 있도록 해준다.

super은 부모 클래스의 constructor을 불러오는 키워드이다. 따라서 super(name)은 cat 클래스의 argument인 name이 animal 클래스의 constructor로 넘어가게 되어서, this._name = name;를 사용할 수 있게 되는것이다.

child class도 method 작성 가능함.

Static Methods

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];
  }
}

class안에 생성하여 클래스 전체에 필요한 기능을 만들때 사용할 수 있다.
instance들은 접근 할 수 없지만, extends를 사용하면 하위 class로 상속 된다.
static 키워드를 통해 만들 수 있다.

0개의 댓글