본문 바로가기

Tech/[Lang] JS & TS

클래스

Hi, There!
안녕하세요, 바오밥입니다.


목차

  1. 개요
  2. 본문
  3. Reference

개요

자바스크립트의 클래스에 대해서 정리하여 알아보았습니다.


본문

객체를 만드는 방법

class 키워드 없이 만들어진 객체는 객체의 property에 선언됩니다.

const User = function(name, age) { // 객체의 property로 선언됩니다.
  this.name = name;
  this.age = age;
  this.showName = function() {
    console.log(name);
  }
}

const mike = new User("mike", 21);
// class 키워드 없이 만들어진 객체는 메서드가 생성 객체의 property에 선언됩니다.

 

이전 장(상속과 프로토타입 (baobab.live))을 참고하면 더욱 수월하게 이해가 가능합니다.

class 키워드로 만든 객체처럼 prototype의 객체 메서드를 숨기고 싶다면 개별적으로 선언해 줘야 합니다.

const User = function(name, age) { // 객체의 property로 선언됩니다.
  this.name = name;
  this.age = age;
}

User.prototype.showName = function() {
  console.log(this.name);
}

const mike = new User("mike", 21);

 

class를 이용하여 객체를 만드는 방법

class 키워드를 통해 만들어진 객체는 prototype의 property에 선언됩니다.

class User2 { // prototype에 선언됩니다.
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }
  showName() {
    console.log(name);
  }
}

const tom = new User2("tom", 11);
// class 키워드를 통해 만들어진 객체는 prototype의 property에 선언됩니다.

 

class 키워드를 사용하여 만들어진 객체는 new 키워드를 반드시 사용해야 합니다.

class User2 { // prototype에 선언됩니다.
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }
  showName() {
    console.log(name);
  }
}

const tom = User2("tom", 11);
// Uncaught TypeError: Class constructor User2 cannot be invoked without 'new' 

 

class 키워드를 사용하여 만들어진 객체의 메서드는 for in 문에서 제외됩니다.

class User2 { // prototype에 선언됩니다.
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }
  showName() {
    console.log(name);
  }
}

for (const a in tom) {
  console.log(a) // "name", "age"
}

 

클래스를 '상속' 하는 방법

extends 키워드를 이용하여 다른 클래스의 프로퍼티를 상속 받을 수 있습니다.

class Car {
  constructor (color) {
    this.color = color;
    this.wheels = 4;
  }

  drive() {
    console.log("drive!!");
  }

  stop() {
    console.log("stop!!");
  }
}

class Bmw extends Car {
  park() {
    console.log("park!!")
  }
}

const z4 = new Bmw("black")

z4.drive() // 상속 덕분에 Car 클래스의 메서드를 사용할 수 있습니다.

 

상속 받은 클래스의 메서드를 '오버라이딩' 하는 방법

상속 받은 클래스의 메서드 동작 말고, 다른 동작이 필요한 경우가 있습니다. 이러한 경우 메서드를 덮어씌우면 같은 이름, 다른 동작으로 구현할 수 있는데 이를 '오버라이딩' 이라고 합니다.

class Car {
  constructor (color) {
    this.color = color;
    this.wheels = 4;
  }

  drive() {
    console.log("drive!!");
  }

  stop() {
    console.log("stop!!");
  }
}

class Bmw extends Car {
  park() {
    console.log("park!!")
  }
  stop() {
    console.log("stop break !!!!!");
  }
}

const z4 = new Bmw("black")

z4.stop() // 메서드가 오버라이딩 되어 "stop break !!!!!" 가 출력됩니다.

 

만약, 같은 이름의 메서드를 '기능'만 확장 시키고 싶은거라면 'super' 키워드를 이용할 수 있습니다.

class Car {
  constructor (color) {
    this.color = color;
    this.wheels = 4;
  }

  drive() {
    console.log("drive!!");
  }

  stop() {
    console.log("stop!!");
  }
}

class Bmw extends Car {
  park() {
    console.log("park!!")
  }
  stop() {
    super.stop(); // 부모 클래스의 stop 메서드를 그대로 상속 받습니다.
    super.drive(); // 부모 클래스의 drive 메서드를 그대로 상속 받습니다.
    console.log("stop break !!!!!");
  }
}

const z4 = new Bmw("black")

z4.stop() // "stop break !!!!!", "stop!!", "drive!!"

 

상속 받은 클래스에서 생성자 함수를 정의할 경우 반드시 부모 클래스의 생성자 함수를 우선적으로 실행해야 합니다.

class Car {
  constructor (color) {
    this.color = color;
    this.wheels = 4;
  }

  drive() {
    console.log("drive!!");
  }

  stop() {
    console.log("stop!!");
  }
}

class Bmw extends Car {
  constructor(color, ownerName) {
    super(color); // 부모 클래스의 생성자 함수 호출 및 매개 변수 전달
    this.ownerName = ownerName;
  }

  park() {
    console.log("park!!")
  }
  stop() {
    super.stop();
    super.drive();
    console.log("stop break !!!!!");
  }
}

const z4 = new Bmw("black", "jhkim")

console.log(z4.ownerName) // "jhkim"

 


Reference

'Tech > [Lang] JS & TS' 카테고리의 다른 글

async, await에 대해서  (0) 2021.10.14
promise에 대해서  (0) 2021.10.12
상속과 프로토타입  (0) 2021.10.05
함수 호출 메서드 (call, apply, bind)  (0) 2021.09.27
스케쥴링 메서드 (setTimeout, setInterval)  (0) 2021.09.24