타입스크립트 클래스를 다루기 전에
자바스크립트 클래스를 정리한다.
https://velog.io/@vieowf23r/프론트엔드-복습-정리-23-프로토타입-new-class-객체지향
참조.
추가할 내용들 후술.
class Player {
score = 0; // 생성자 함수 밖.
numLives = 10; // 클래스 필드를 이용한 것.
constructor(first, last) {
this.first = first;
this.last = last;
}
taunt() {
console.log("Boo");
}
}
생성자 함수 밖에서 프로퍼티를 정의할때 하드 코딩된 값을 추가 가능.
class Player {
#score = 0; // # 을 추가했다
numLives = 10;
constructor(first, last) {
this.first = first;
this.last = last;
}
getScore() {
return this.#score; // 이렇게 클래스 안에서는 사용 가능하다.
}
taunt() {
console.log("Boo");
}
}
클래스 밖에서 건드리지 못하게 하는 기능이다.
해시 # 기호를 붙인다. #로 시작하는 프로퍼티가 있다면 이는 해당 클래스 안에서만 사용할 수 있다.
밖에서 해당 프로퍼티에 액세스할 수 없다.
객체 접근자.
부가적인 로직을 추가하거나 프로퍼티처럼 보이는 합성 프로퍼티를 쉽게 만들 수 있다.
class Player {
#score = 0; // # 을 추가했다
numLives = 10;
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() { // getter
return `${this.first} ${this.last}`;
}
get score() { // 이 코드는 아래 코드와 같은 기능을 한다.
return this.#score;
}
getScore() {
return this.#score;
}
taunt() {
console.log("Boo");
}
}
console.log(player1.fullName);
console.log(player1.getScore()); // 이 코드와 같지만
console.log(player1.score) // 이렇게 접근 가능하다.
get Score()와 getScore() 는 같은 기능을 한다. 하지만 더 깔끔하게 작성가능.
class Player {
#score = 0;
numLives = 10;
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() { // getter
return `${this.first} ${this.last}`;
}
set fullName(newName) { // 새로운 이름을 받아서 나눈 후, 새로 first와 last로 지정.
const [first, last] = newName.split(" ");
this.first = first;
this.last = last;
}
get score() {
return this.#score;
}
set score(newScore) { // set으로 새 점수를 받을수 있다.
if(newScore < 0) { // 이렇게 조건을 붙여서 로직을 더할수도 있다.
throw new Error("Score must be positive!")
}
this.#score = newScore;
}
taunt() {
console.log("Boo");
}
}
앞서 프라이빗 필드는 외부에서 액세스가 불가능 하다고 했다.
그러나 set을 이용하면 업데이트가 가능하다.
class Player {
static description = "Player in our gmae"; // static 키워드 뒤
score = 0;
numLives = 10;
constructor(first, last) {
this.first = first;
this.last = last;
}
static randomPlayer() { // 새로운 인스턴스를 만드는 정적 함수.
new Player("andy", "Samberg");
}
taunt() {
console.log("Boo");
}
}
const player1 = new Player("adams", "rock")
console.log(player1.description) // 에러.
console.log(Player.description) // "Player in our gmae"
static 키워드 뒤에 프로퍼티를 만들면 개별 인스턴스가 아닌 Player 클래스에만 존재한다.
클래스 자체에만 속한다.
특정 인스턴스와 관련 없으면서 클래스 자체와 연관된 기능을 클래스로 그룹화 할 수 있게 해준다.
주로 생성 메서드 혹은 새로운 인스턴스나 여러 인스턴스를 생성하는 헬퍼 등.