오늘은 자바스크립트의 클래스에 대해서 알아볼 것이다ㅏ
먼저 알아볼 것은 자바스크립트를 나누는 법이다
//example.js
export const data = [1, 2, 3];
//chellenge.js
export const add = (a, b) => a + b;
//index.js
import { data } from "./example";
let updatedData = data;
updatedData.push(5);
console.log(updatedData);
console.log(add(1, 10));
//11
이런 식으로 불러와서 사용할 수 있다
함수, 변수모두 가능하다.
클래스 Class 문법을 알아보자
export class Animal {
constructor(type, legs) {
this.type = type;
this.legs = legs;
}
makeNoise(sound = "Loude Noise") {
console.log(sound);
}
get metaData() {
return `Type= ${this.type}, legs=${this.legs}`;
}
static return10() {
return 10;
}
}
export class Cat extends Animal {
makeNoise(sound = "meow") {
console.log(sound);
}
}
Animal 은 생성자로 type와 legs를 받아 만든다
Animal은 Getter로 metaData라는 함수를 구성해 클래스 내부 필드를 가져온다
import { Animal, Cat } from "./animal";
let dog = new Animal("dog", 4);
let cat = new Cat("cat", 4);
console.log(dog, cat);
Cat은 Animal을 상속받아 클래스를 구성하고 있다
makeNoise를 오버라이딩해 사용한다
Animal {type: "dog", legs: 4, constructor: Object}
Cat {type: "cat", legs: 4, constructor: Object}
이런 모습이 콘솔에 찍힐 것이다
오늘은 Class에 대해서 겉핥기 해보았다
다음에 더 자세하게 작성할 것이다
'JS' 카테고리의 다른 글
JS - ES6 문법 파헤치기 (3) (0) | 2023.03.22 |
---|---|
JS - ES6 문법 파헤치기 (1) (0) | 2023.03.09 |