class
라는 기능이 없었기 때문에 prototype
을 사용하여 객체생성자를 상속하였다.prototype
을 조금 더 쉽게 사용하기 위해 만들어진 문법class Animal{
constructor(type, name, sound){ //constructor = 생성자
this.type = type;
this.name = name;
this.sound = sound;
}
say(){
console.log(this.sound);
}
}
//say함수를 class 내부에 구현을 해주었는데, 함수를 만들게 되면 자동으로 prototype으로 등록됨
// console.log(Animal.prototype.say); //함수가 설정되어있는 것을 볼수가 있다.
class Dog extends Animal{
constructor(name, sound){
super('강아지', name, sound);
}
}
class Cat extends Animal{
constructor(name, sound){
super('고양이', name, sound);
}
}
/*
1. extends 키워드가 Animal class를 상속 받음
2. constructor가 기존 Animal에서 사용하는 constructor를 덮어쓴다.
3. 그 과정에서 super키워드를 사용해서 Animal이 가지고 있는 constructor를 먼저 호출하고나서 자신이 해야될 일을 처리 할 수 있다.
*/
const dog = new Dog('재롱이', '왈왈!');
const cat = new Cat('비키', '먀옹~');
//계속 다른 객체들을 만들 수 있다.
const cat2 = new Cat('길용이','먀앙');
const cat3 = new Cat('나비','먀!');
dog.say(); //"왈왈!"
cat.say(); //"먀옹~"
cat2.say(); //"먀앙"
cat3.say(); //"먀!"
class Food {
constructor (name) {
this.name = name;
this.brands = [];
}
//주로 클래스 내부에 구현하는 함수를 메서드라고 한다.
addBrand(brand) {
this.brands.push(brand)
}
print() {
console.log(`${this.name}을/를 파는 음식점들 : `);
console.log(this.brands.join(', '));
}
}
const pizza = new Food('피자');
pizza.addBrand('피자헛');
pizza.addBrand('도미노');
const chicken = new Food('치킨');
chicken.addBrand('굽네치킨');
chicken.addBrand('BBQ');
pizza.print();
chicken.print();
class Food
를 만들어서 constructor (name)
의 name
파라미터를 가져오게 되면new Food('피자')
, new Food('치킨')
이 name
파마리터로 날라와서 this.name
으로 설정이 된다.new
키워드를 사용해서 새로운 Food
객체가 만들어질 때 그안에 this.brands = [];
배열이 들어가 있게 되고addBrand()
라는 메서드를 만들었는데, pizza.addBrand('피자헛');
, chicken.addBrand('굽네치킨');
문자열 브랜드 이름을 가져와서 this.brands = [];
배열에다가 넣어주는 작업을 해줬다.print(){}
에서는 현재 가지고 있는 name
값과 현재의 brands
의 값을 출력을 하는 함수를 만들고pizza.addBrand
에서 추가하고, 추가해서 print()
를 했더니 결과가 나타난 것이다.클래스 문법을 사용하게 되면, 이런 비슷한 작업을 하게되는 같은 형태를 지닌 객체들의 대해서 객체들의 값이라던지, 아니면 객체가 가지고 있는 함수(메서드)라던지, 그런 것들이 코드 관리를 조금 더 깔끔하게 할 수 있다.
이 글은 패스트캠퍼스 '프론트엔드(React)올인원패키지Online'을 수강하며 정리한 노트입니다.
https://fastcampus.co.kr/search?keyword=%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C