Front-end/타입스크립트로 블록체인 만들기

[TS] Classes

탱 'ㅅ' 2024. 1. 2. 14:10

객체지향 프로그래밍 - JS에는 없는 개념

 

1. 생성자 자동 생성

생성자의 파라미터를 써주기만 하면 consturctor() 함수 자동 생성

// TypeScript
class Player {
	constructor (
		private firstName: string,
		private lastName: string
	) {}
}

// JavaScript
class Player {
	cosntructor (firstName, lastName) {
		this.firstName = firstName
	}
}

 

 

2.

추상 클래스 (abstract class)

오직 다른 클래스에서 상속받을 수만 있는 클래스

직접 인스턴스 생성(인스턴스화) 불가

 

추상 메소드

추상 클래스 안에서 구현(implemetation)하지 않고 call signature만 작성한 다음

상속받은 자식 클래스에서 반드시 구현해야 한다.

 

 

 

3. 접근 제한자 (access modifier)

: property 뿐만 아니라 method에도 적용✕

private으로 만든다면 해당 추상 클래스를 상속받았을지라도 접근할 수 없다.

public 생략 불가

 

접근 여부 해당 추상 클래스  상속받은 자식 클래스 인스턴스 외부
public
protected
private

 

abstract class User {
	constructor (
		private firstName: string,
		private lastName: string,
		protected nickName: string
    ) {}
    
    abstract getNickName(): void
    getFullName() {
		return `${this.firstName} ${this.lastName}`
    }
} 

class Player extends User {
	getNickName() {
		console.log(this.nickName)
    }
}

const tang = new Player("taeyong", "lim", "tang") // new User() ❌

tang.getFullName()
🚫 tang.nickName

 

 

⚑ readonly

private / protected 외 public readonly

파라미터로 전달해서 값은 보여주고싶지만, 인스턴스 외부에서 함부로 접근은 못 하게 하고 싶을 때

 

 static

클래스에는 static 멤버가 있을 수 있습니다.

이 멤버는 클래스의 특정 인스턴스와 연결되지 않습니다.

클래스 생성자 객체 자체를 통해 접근할 수 있습니다. 

어떤 특정한 객체가 아닌 클래스에 속한 함수를 구현하고자 할 때

in JS

 

ref. MDN static  정적 메소드와 정적 프로퍼티

 

type Words = {
	// index signature: 변수명은 모르고 key, value의 type만 알 경우
	[key: string]: string
}

class Dict {
	// 생성자 수동으로 초기화
	private words: Words
	constructor() {
	    this.words = {}
	}
    
    // 단어 추가
    add(word: Word) { // class를 parameter type으로서 사용 
		if (this.words[word.term] === undefined) { // 사전에 없으면
			this.words[word.term] = word.def
		}
    }
    // 단어의 정의 
    def(term: string) { 
		return this.words[term]
    }
    // 단어 삭제
    remove(term: string) {
    	if (this.words[word.term !== undefined) {
        	delete this.words[term]
        }
    }
    static hello() {
		return "hello"
	}
}

class Word {  // type으로 사용
	constructor(
		// Dict 클래스에 보내서 탐색할 수 있어야하기 때문에 public
		// but, 인스턴스 외부에서 접근할 수 있는 불상사가..!🙅🏻‍♀️🙅🏻‍
		// 값을 보여주고는 싶지만 수정은 불가능하게 하고 싶어 => public readonly
		// public 생략 불가
		public readonly term: string,
		public readonly def: string
    ) {}
}

const kimchi = new Word("kimchi", "한국의 음식")
kimchi.def = "blahblah" // public
🚫 kimchi.def = "blahblah" // public readonly

const dict = new Dict()
dict.add(kimchi)
dict.def("kimchi")  // 한국의 음식

Dict.hello() // static method

 

 

index signature

 

Documentation - Classes

How classes work in TypeScript

www.typescriptlang.org