Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

바스키아

TypeScript 클래스 (Class Type) 본문

JS/TypeScript

TypeScript 클래스 (Class Type)

바스키아1 2019. 8. 29. 16:45

es6에 등장한 class키워드는 함수를통해 만들었던걸 클래스를 통해 특정타입의 객체를 사용할수도 있다.

 

우선 es6의 class 키워드 예제를 보자  ( 자세한 es6는 따로 정리해놓겠다. )

class Cart {
    constructor(user) {
        this.user = user;
        this.store {};
    }
    put(id, project) {
        this.store[id] = product;
    }
    get(id) {
        return this.store[id];
    }
}
const cart1 = new Cart({name : 'john'});
const cart2 = new Cart({name : 'jay'});

사질 자바 하던사람은 굉장히 반가울거 같다는 생각이 든다. 클래스 객체지향에 constructor 생성자 보이구 

new연산자로 객체 생성이라... 나의 입장에서는 반갑기만하다.(사실 자바스크립트 한지얼마안되서 반가운거모름)

 

이제 여기서 타입을 부여해보는 Time을 가져보겠다.

 

interface User {
    user : string;
}
interface Product {
    id: string;
    price : number;
}
class Cart {
    user : User;
    store : object;
    constructor(user : User) {
        this.user = user;
        this.store {};
    }
    put(id : string, product : Product) {
        this.store[id] = product;
    }
    get(id : string) {
        return this.store[id];
    }
}
const cart1 = new Cart({name : 'john'});
const cart2 = new Cart({name : 'jay'});

typescript에서 user라는 속성을 class 바디 에다가 정의해야한다 .

 

이로서 class안에 두개의 속성과(user, store) , 생성자 , 두개의 함수인 카트를 정의했다. 

 

여기서 접근제한자 private public protected 를 사용하면 객체를 생성해서 내부 속성에 제한을 할수있다.

(자바랑 같은 개념이라 디테일하게 설명 안할꺼야)

만약 저 store : object; 라고 클래스 내부에 선언한 속성에 private를 접근제한자 선언을 하면

ex)

...
class Cart {
	user : User;
    private store : object;
    constructor(user : User){
  ...
  ...
    

cart1.user  는 접근이 가능하겠지만

cart1.store 는접근 할수가 없는거야 u know? 

 

public private protected 차이 알고싶음 따로 찾아.... 

 

--작성중.... --- 이어서 쓸꺼니까 건들지마

 

'JS > TypeScript' 카테고리의 다른 글

TypeScript) Intersection & Union Types  (0) 2019.09.12
TypeScript) tsconfig.ts 설정하기  (0) 2019.08.31
TypeScript Enum  (0) 2019.08.29
TypeScript 함수형 타입(function Type)  (0) 2019.08.29
TypeScript 인터페이스(Interface)  (0) 2019.08.29