반응형
1. 클래스 사용방법
Class는 선언식과 표현식 두 가지 방법으로 사용할 수 있다.
* Class 선언
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
함수 선언과 클래스 선언의 중요한 차이점은 함수 선언의 경우 호이스팅이 일어나지만,
클래스 선언은 호이스팅이 제한되어 클래스를 사용하기 위해서는 클래스를 먼저 선언 해야한다.
즉, 클래스를 선언한 후에만 객체를 생성할 수 있다.
const p = new Rectangle(); // 클래스를 선언하지 않아 에러발생
class Rectangle {}
▶ Class 표현식
클래스 표현식은 이름을 가질 수도 있고, 가지지 않을 수도 있다.
(1) 클래스 이름이 없는 표현식
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// 출력: "Rectangle"
(2) 클래스 이름이 있는 표현식
이름을 가진 클래스 표현식의 이름은 클래스의 body에 대해 local scope에 한해 유효하다.
let Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// 출력: "Rectangle2"
+) 이외에 클래스에 method를 정의하거나, 자식클래스에 클래스 상속(extends), super 키워드를 통해 상위클래스를 호출 할 수 있다.
#참고사이트
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes#class_%EC%A0%95%EC%9D%98
반응형
'Frontend > JavaScript' 카테고리의 다른 글
[JS] ES6의 구조 분해 문법 (Destructuring) (0) | 2021.08.23 |
---|---|
[JS] 시간 지연 함수 setTimeout() (0) | 2021.08.21 |
[JS] 자바스크립트로 버튼 비활성화 하기 (0) | 2021.08.18 |
[JS] 노드의 종류와 관계 (0) | 2021.08.16 |
[JS] 자바스크립트 form 이벤트 (0) | 2021.08.15 |
최근댓글