강좌 : 유튜브 드림코딩 by 엘리
field(속성)
와 method(행동)
값이 들어가고 field값만 들어있는 경우 data class
라고 부른다// 예시
class person{
name; // 속성(field)
age; // 속성(field)
speak(); // 행동(method)
}
new
라는 키워드를 이용this
: 생성된 object// 예시
class Person {
constructor(name, age) { // constructor(생성자)
// fields
this.name = name;
this.age = age;
}
speak() { // method
console.log(`${this.name}: hello!`);
}
}
const hxxjxx = new Person('hxxjxx', 20); // object
console.log(hxxjxx.name); // hxxjxx
console.log(hxxjxx.age); // 20
hxxjxx.speak(); // hxxjxx: hello!
get
키워드를 이용해서 값을 return
한다set
키워드를 이용해서 값을 설정 그래서 value
를 받아와야한다데이터를 읽어오는 것이 아니라 getter을 호출
메모리의 값을 업데이트하는 것이 아니라 setter를 호출
하게되고 이것이 반복되서 call stack이 발생
한다기호(_)
등 을 이용해서 만들어준다// 예시
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
// if (value < 0) { // 이와같이 사용할수도 있지만 아래와 같이 사용하는게 좋다
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value; // age값이 -1이기 때문에 0을 반환
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age); // 0
해시태그(#)
를 붙여 정의// 예시
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); // 2
console.log(experiment.privateField); // undefined
static
키워드를 사용하면 object와 상관없이 class 자체에 연결
// 예시
class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.articleNumber); // 1
console.log(Article.publisher); // Dream coding
// console.log(article1.publisher); // undefined
Article.printPublisher(); // Dream coding
extends
키워드를 이용해서 재사용재정의(overriding)
해서 사용가능super
을 사용하면 부모함수와 overriding을 같이 사용할 수 있다// 예시
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {} // 새로운 Rectangle class에 shape을 연장
class Triangle extends Shape { // shape을 연장
draw() { // overriding
super.draw(); // 부모함수 호출
console.log('🔺');
}
getArea() { // overriding
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drawing blue color!
console.log(rectangle.getArea()); // 400
const triangle = new Triangle(20, 20, 'red');
triangle.draw(); // drawing blue color! // 🔺
console.log(triangle.getArea()); // 200
console.log(rectangle instanceof Rectangle); // t
console.log(triangle instanceof Rectangle); // f
console.log(triangle instanceof Triangle); // t
console.log(triangle instanceof Shape); // t
console.log(triangle instanceof Object); // t