ES6 class

jini.choi·2022년 5월 17일
0

JavaSctipt-입문

목록 보기
8/10
  • javascript는 이전에 class라는 기능이 없었기 때문에 prototype을 사용하여 객체생성자를 상속하였다.
  • ES6부터는 class라는 문법이 도입되서 코드를 조금 더 간략한 문법으로 구현 할 수 있다.
  • class문법을 사용하면 상속을 해야되는 상황에서 훨씬 쉽게 할 수 있다.
  • 객체 생성사와 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(); //"먀!"

Food Class 만들기

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();
  1. class Food를 만들어서 constructor (name)name파라미터를 가져오게 되면
  2. new Food('피자'), new Food('치킨')name파마리터로 날라와서 this.name으로 설정이 된다.
  3. new키워드를 사용해서 새로운 Food객체가 만들어질 때 그안에 this.brands = []; 배열이 들어가 있게 되고
  4. addBrand()라는 메서드를 만들었는데, pizza.addBrand('피자헛');, chicken.addBrand('굽네치킨'); 문자열 브랜드 이름을 가져와서 this.brands = []; 배열에다가 넣어주는 작업을 해줬다.
  5. 그리고 print(){} 에서는 현재 가지고 있는 name값과 현재의 brands의 값을 출력을 하는 함수를 만들고
  6. 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

profile
개발짜🏃‍♀️

0개의 댓글