패스트캠프 프론트앤드 인강 27일차 자바스크립트의 클래스를 배우고 Food class프로젝트를 하였다.
클래스
자바스크립트에서 es6부터 클래스기능이 추가되었다. 클래스는 프로토타입을 자동으로해주고 상속을 쉽게해준다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Animal{
constructor(type, name, sound){
this.type = type;
this.name = name;
this.sound = sound;
}
say(){
console.log(this.sound);
}
}
const dog = new Animal('dog','doggy','dogdog')
const cat = new Animal('cat','catcy','nahhhh')
dog.say()
cat.say()
</script>
</body>
</html>
say라는 함수를 클래스내부에 구현을 해주었는데 이렇게 함수를 만들게되면 자동으로 프로토타입으로 등록이된다.
그래서 console.log(Animal.protype.say)를 출력할경우 say함수가 설정되어있는모습을 볼수있다.
또다른 클래스문법의 장점은 상속이 쉽다는 점이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
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('dog', name, sound)
}
}
class Cat extends Animal{
constructor(name, sound){
super('cat', name, sound)
}
}
// const dog = new Animal('dog','doggy','dogdog')
// const cat = new Animal('cat','catcy','nahhhh')
const dog = new Dog('강아지','멍멍')
const cat = new Cat('야옹이','야옹')
const cat2 = new Cat('야옹옹', '야오오오옹')
dog.say()
cat.say()
cat2.say()
</script>
</body>
</html>
(예제)Food클래스 만들기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
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('도미노피자')
pizza.print();
</script>
</body>
</html>
프론트엔드 개발 올인원 패키지 with React Online. | 패스트캠퍼스
성인 교육 서비스 기업, 패스트캠퍼스는 개인과 조직의 실질적인 '업(業)'의 성장을 돕고자 모든 종류의 교육 콘텐츠 서비스를 제공하는 대한민국 No. 1 교육 서비스 회사입니다.
www.fastcampus.co.kr
반응형
'Frontend' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 29회차 미션 (0) | 2020.09.07 |
---|---|
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 28회차 미션 (0) | 2020.09.06 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지26회차 미션 (0) | 2020.09.04 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지25회차 미션 (0) | 2020.09.03 |
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지24회차 미션 (0) | 2020.09.02 |