❗ Javascript의 Class는 syntatic suger일뿐 새로운 문법이 아닙니다. prototype의 이해를 기반으로 공부하는 것을 추천합니다. c++나 java의 Class와는 다르게 프로토타입 기반의 언어입니다.
Class는 특별한 함수이다. 다른 함수들과 동일하게 class 표현식과 class 선언식으로 정의할 수 있다.
// class 선언식
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// class 표현식
var Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
constructor 메서드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드이다. "constructor" 라는 이름을 가진 특수한 메서드는 클래스 안에 한 개만 존재할 수 있다.
class PersonCl {
constructor(firstName, birthYear){
this.firstName = firstName;
this.birthYear = birthYear;
}
//Methods will be added to .prototype property
clacAge(){
console.log(2037-this.birthYear);
}
}
const jessica = new PersonCl('Jessica', 1996);
console.log(jessica.__proto__ === PersonCl.prototype);
PersonCl.prototype.greet = function() {
console.log(`Hey ${this.firstName}`)
};
jessica.greet();
console.log(jessica.__proto__ === PersonCl.prototype);를 통해 class 내의 메서드는 기존 프로토타입과 동일함을 확인할 수 있다. 따라서 class 밖에서 프로토타입을 정의하는 것은 class 내부에서 메서드를 정의하는 것과 동일하다.
주의 사항
- 함수 선언과 다르게 class는 호이스팅 되지 않는다.
- class는 일급 시민이다.
- class는 strict mode에서 실행된다
참조
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes
반응형
'JavaScript' 카테고리의 다른 글
[Javascript] Object.create (0) | 2021.10.25 |
---|---|
[Javascript] 상속(Inheritance) (0) | 2021.10.19 |
[Javascript] 이벤트 버블링과 캡처링 (0) | 2021.10.11 |
[Javascript] DOM 노드 (1) | 2021.10.11 |
[Javascript] for of, forEach, map 비교 (0) | 2021.09.29 |