[ES6] Class의 기본

JIOO·2021년 10월 8일
0

ES6

목록 보기
3/17

Extend

👩‍🎓 Extends란?

Class문법을 복사할 때 쓰는 문법

class Animal {
  constructor(name, age, sound) {
    this.name = name;
    this.age = age;
    this.sound = sound;
  }

  makeSound() {
    console.log(this.name + "이(가)" + this.sound + " 소리를 냅니다.");
  }
}

// 기존 클래스 문법

class Dog extends Animal {
  //새로운 클래스명 + extends 복사할 클래스명
  constructor(breed) {
    this.breed = breed;
  }
  newFunc() {
    console.log(this.breed);
  }
}
const myDog = new Dog("강아지");

이때 복사한 클래스의 데이터나 함수를 쓰고 싶을 때 사용 하는 것이 Super


constructor

super

super을 사용 할땐 constructor에 복사한 클래스의 인자들 + 새로운 인자를 넣어주고
super(복사한 클라스의 인자들 그대로 기입) 을 그냥 들고와 써주면됨

💡 코드 예제

class Animal {
  constructor(name, age, sound) {
    this.name = name;
    this.age = age;
    this.sound = sound;
  }

  makeSound() {
    console.log(this.name + "이 " + this.sound + " 소리를 냅니다.");
  }
}

/// 기존 클래스 문법


class Dog extends Animal {
  //새로운 클래스명 + extends 복사할 클래스명
  constructor(name, age, sound, breed) {
    // 클래스가 복사되니 constructor에 담기는 인자들도 복사 + 새로운 클래스에 들어갈 인자
    super(name, age, sound); // 부모 클래스 생성자 호출
    this.breed = breed;
  }
  newFunc() {
    super.makeSound(); // animal 클래스의 함수를 가져옴
    console.log(this.breed);
  }
}
const myDog = new Dog("맥스", 3, "멍멍", "강아지");

// 부모 클래스의 메서드 호출
myDog.newFunc(); // 맥스이 짖습니다.

super을 이용한 함수를 사용할 땐 이렇게 ↓


  newFunc() {
    super.makeSound(); // animal 클래스의 함수를 가져옴
    console.log(this.breed);
  }
  
 또는 
 
  newFunc2() {
   const soundInfo = super.makeSound(); // 부모 클래스의 makeSound 메서드 호출
    const breedInfo = this.name + '의 품종은 ' + this.breed + '입니다.';
    const result = soundInfo + ' ' + breedInfo;
    return result
    // 맥스이(가) 멍멍 소리를 냅니다. 맥스의 품종은 강아지입니다.
  }   

예제

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

// 데이터 배열
const peopleData = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
  { name: "Bob", age: 28 },
  // 추가적인 데이터를 필요한 만큼 추가할 수 있습니다.
];

// Person 객체를 담을 배열
const peopleArray = [];

// 반복문을 통해 자동으로 객체 생성하고 배열에 추가
for (const data of peopleData) {
  const person = new Person(data.name, data.age);
  peopleArray.push(person);
}

// 배열 출력
console.log(peopleArray);

static

class에서의 statc이란 class 인스턴스를 생성하지 않고 바로 내부 함수를 호출 하는 방식

before

// 클래스의 인스턴스 생성
const myInstance = new MyClass(42);

// 인스턴스를 통해 메소드 호출
console.log(myInstance.getValue()); // 출력: 42

// 정적(static) 메소드 직접 호출
MyClass.sayHello(); // 출력: Hello from MyClass!

after

class MyClass {
  constructor(value) {
    this.value = value;
  }

  getValue() {
    return this.value;
  }

  static sayHello() {
    console.log('Hello from MyClass!');
  }
}

// 인스턴스를 생성하지 않고 정적(static) 메소드 직접 호출
MyClass.sayHello(); // 출력: Hello from MyClass
// 이렇게 클래스 함수를 바로 실행 가능 

추가 정보

profile
프론트엔드가 좋은 웹쟁이 with Notion (요즘은 노션과 병행 중)

0개의 댓글