요즘 javascript 공부하는 게 재밌는 것 같다.+ 20220322의 홍두현이 과거에 홍두현에게 "그거 아니야..... 제발 정신 차려..."
Food 예제
이번 예제에서는 음식과 음식점, 그리고 위치를 class로 나타내는 예제를 만들어 보려고 한다.
먼저 class를 만들어주고 작성할 때는 앞을 무조건 대문자로 해준다.
class를 만들었으면 그 안에 constructor 즉, 생성자를 만들어주고 파라미터에 내가 넣고 싶은 값을 넣는다.
class Food {
constructor(name) {
this.name = name;
this.locations = [];
this.brands = [];
}
}
예시를 Food로 했기 때문에 pizza 와 chicken으로 해보겠다.
표현할 값들은 name location brands로 정했다.
this에는 brands와locations라는 비어있는 배열을 넣어줬다. 값들이 문자열로 들어오는 공간이다.
this.name과 빈 배열을 활용하는 메서드를 작성해 보자
class 내부에 작성하는 함수를 메서드라고 부른다.
class Food {
constructor(name) {
this.name = name;
this.locations = [];
this.brands = [];
}
addBrand(brand) {
this.brands.push(brand);
}
addLocation(local) {
this.locations.push(local);
}
print() {
console.log(`${this.locations}에서 ${this.name}을/를 파는 음식점들 :`);
console.log(this.brands.join(", "));
}
}
먼저 addBrand라는 메서드를 적어줬다. 이 메서드가 하는 건 파라미터 brand로 받아온 값들을 constructor에 있는 brands라는 배열에 push해주는 역할을 한다. addLocation도 동일한 역할을 한다.
그리고 print 메소드로 콘솔창에 직접 입력이 될 수 있도록 작성을 하는데 templete literal로 좀 더 간결하게 작성해 주고 locations와 name의 위치를 잡아준다.
두 번째로 brands의 join()으로 배열 안에 있는 원소들을 ,와 space bar를 통해 합쳐서 리스트처럼 보이게 만들어준다.
이제 pizza라는 변수를 생성해서 값을 넣어보도록 하겠다.
class Food {
constructor(name) {
this.name = name;
this.locations = [];
this.brands = [];
}
addBrand(brand) {
this.brands.push(brand);
}
addLocation(local) {
this.locations.push(local);
}
print() {
console.log(`${this.locations}에서 ${this.name}을/를 파는 음식점들 :`);
console.log(this.brands.join(", "));
}
}
const pizza = new Food("피자");
pizza.addBrand("피자헛");
pizza.addBrand("도미노피자");
pizza.addLocation("인천");
const chicken = new Food("치킨");
chicken.addBrand("굽네치킨");
chicken.addBrand("네네치킨");
chicken.addLocation("부천");
pizza.print();
chicken.print();
pizza와 chicken을 변수로 선언해 주고new Food에 name을 전달하고 그 후 addBrand와 addLocation에 값을 전달해 주고 아까 저장한 print를 불러오게 된다면 값은 이와 같이 나온다.
인천에서 피자를/를 파는 음식점들 :
피자헛, 도미노피자
부천에서 치킨을/를 파는 음식점들 :
굽네치킨, 네네치킨
처음엔 좀 헷갈렸지만 예제를 해봄으로써 처음보단 좀 더 이해가 된다. 다른 예제들을 계속 추가해서 얼른 익숙하게 만들어야겠다.
Shape 예제
220218 추가 예제
이번 예제에선 너비와 높이, 그리고 색상을 받아 사각형과 삼각형을 그려보고 상속과 다양성을 좀 더 사용해 보는 예제를 해보겠다.
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`이 ${this.color}로 그려봅시다.`)
}
getArea() {
return this.width * this.height;
}
}
먼저 Shape이라는 class를 만들어서 안에 constructor 즉, 생성자를 이용해서 오브젝트를 만들 때 필요한 데이터를 전달하려고 width,height,color를 받아오기로 했다.
draw()와 getArea라는 함수 두 개를 만들어줬는데 draw는 콘솔창에 뿌려줄 내용이고 getArea는 바로 리턴을 하는 값이다.
class Rectangle extends Shape {}
class Triangle extends Shape {}
const rectangle = new Rectangle(20,20,'파랑');
const triangle = new Triangle(20,50,'빨강');
extends를 사용해 줌으로써 Shape를 상속받아서 Rectangle과 Triangle을 따로 작성해 보겠다.
이렇게만 봤을 땐 extends 쪽에 별 다른 내용이 안 들어가도 될 것 같은데 삼각형은
(너비 * 높이)/2로 기존 코드와는 다르게 계산을 해줘야 한다. 기존에 상속 받은 코드를 고쳐야하는데 이때 extends에 작성을 해줘야한다.
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`이 ${this.color}로 그려봅시다.`)
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('🔺')
}
getArea () {
return (this.width * this.height)/2;
}
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20,50,'red');
triangle.draw();
console.log(triangle.getArea());
//drawing blue color of
//400
//drawing red color of
//🔺
//500
전체 코드를 작성하면 이렇게 나온다. draw()에 super를 사용했는데 {} 안에 아무것도 넣지 않아도 되지만 전부 공통적으로 쓰는데 만약에 특정 부분이 바뀌어야 한다면 필요한 함수를 재정리해서 쓸 수 있다. 이걸 overwrite라고 한다. 하지만 작성 시 원래 있던 상위 class의 내용이 지워지는데 super를 사용하면 상위 class의 내용도 가져올 수 있다.
REFERENCE
드림코딩 by 엘리 : https://www.youtube.com/watch?v=JB_yU6Oe2eE&t=1452s
'Javascript' 카테고리의 다른 글
[javascript] 비동기 처리 (0) | 2023.01.16 |
---|---|
[javascript] spread (0) | 2023.01.16 |
[javascript] - 07 프로토타입과 클래스 - es6 class (0) | 2023.01.16 |
[javascript] - 07 프로토타입과 클래스 - 객체 생성자 상속받기 (0) | 2023.01.16 |
[javascript] 6. 배열 내장 함수 - test (0) | 2023.01.16 |
댓글