Javascript - Class

YuJin Lee·2020년 10월 7일
0

Javascript

목록 보기
12/22
  • Class
    ES6에서 추가된 문법이다.
    class는 C++, Java, C#, PHP 등의 다른 프로그래밍 언어에는 있는 기능지만
    Javascript에는 없어서 객체생성자를 사용하여 비슷한 작업을 구현했다.
    class를 사용하면 객체생성자로 구현했던 코드를 좀 더 깔끔하게 구현할 수 있으며 상속도 훨씬 쉽게 할 수 있다.

// Animal이라는 class를 만든다.
class Animal {
  // counstructor - 생성자
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

console.log(Animal.prototype.say);
// function say() {}


// Dog이라는 class를 만든다.
// extends - 특정 클래스를 상속받는다
class Dog extends Animal {
  // Animal의 constructor를 덮어쓴다.
  constructor(name, sound) {
    // super - 자신이 상속받은 클래스의 constructor(생성자)를 호출한다.
    super('개', name, sound);
  }
}

class Cat extends Animal {
  constructor(name, sound) {
    super('고양이', name, sound);
  }
}

// 파라미터값을 넣은 class Dog과 Cat을 변수에 담는다. 
const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');
const dog2 = new Dog('뭉뭉이', '뭉뭉');

dog.say(); // 멍멍
cat.say(); // 야옹
dog2.say(); // 뭉뭉

  • 또 다른 예시
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  area() {
    return this.height * this.width;
  }
};

// 변수에 class 값을 담아 다음과 같이 사용할 수 있다.
const rectangle1 = new Rectangle(5,8).area();
console.log(rectangle1); // 40

const rectangle2 = new Rectangle(4,9).area();
console.log(rectangle2); // 36
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글