Javascript 의 class

유다송·2023년 8월 15일
0

JavaScript

목록 보기
8/8
post-thumbnail

class란?

  • 객체를 생성하기 위한 템플릿
  • class를 통해 원하는 구조의 객체 틀을 짜놓고, 비슷한 모양의 객체를 찍어낼 수 있다.
  • 문법적으로 기능은 그대로인데 코드의 양을 줄여주고 직관적으로 쉽게 코드를 읽을 수 있게 만들어 준다.

비슷한 객체를 찍어내기 위해 사용했던 것

생성자

// 생성자
function Person({name, age}) {
   this.name = name;
   this.age = age;
}

Person.prototype.introduce = function() {
   return `안녕하세요, 제 이름은 ${this.name}입니다.`;
};

const person = new Person({name: 'Tom', age: 19});
console.log(person.introduce()); // 안녕하세요, 제 이름은 Tom입니다.

class

class Person {
   // 이전에서 사용하던 생성자 함수는 클래스 안에 `constructor`라는 이름으로 정의한다.
   constructor({name, age}) { // 생성자
     this.name = name;
     this.age = age;
   }
   // 객체에서 메소드를 정의할 때 사용하던 문법을 그대로 사용하면, 메소드가 자동으로 `Person.prototype`에 저장된다.
   introduce() {
     return `안녕하세요, 제 이름은 ${this.name}입니다.`;
   }
}

const person = new Person({name: 'Peter', age: 19});
console.log(person.introduce()); // 안녕하세요, 제 이름은 Peter입니다.
  • ES6 이전엔 프로토타입 체이닝으로 class와 비슷하게 구현했었음.

Javascript ES6 class 문법

class 선언

class Person {
   height = 180; // 인스턴스 변수

   // constructor는 이름을 바꿀 수 없다.
   constructor(name, age) {
      // this는 클래스가 생성할 인스턴스를 가리킨다.
      this.name = name;
      this.age = age;
   }
}

let person1 = new Person('john', 23);
console.log(person1.name); // john
console.log(person1.age); // 23
console.log(person1.height); // 180
  • constructor는 인스턴스를 생성하고 클래스 필드를 초기화하기 위한 특수한 메서드이다.
  • constructor는 클래스 안에 한 개만 존재할 수 있다. 2개 이상 있을 경우 Syntax Error가 발생하니까 주의.

class 메소드 정의

class Calculator {
   add(x, y) {
     return x + y;
   }
   subtract(x, y) {
     return x - y;
   }
 }
 
 let calc = new Calculator();
 calc.add(1,10); // 11

class 상속

class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

class Dog extends Animal {
  constructor(name, sound) {
    super('개', name, sound); // super 함수가 상속받은 클래스의 생성자를 가르킨다.
  }
}

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

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

💡 추가자료 : 자바스크립트 클래스 문법 - 완벽 가이드

클래스

1개의 댓글

comment-user-thumbnail
2023년 8월 15일

글 잘 봤습니다.

답글 달기