Front-end/Typesrcipt

Typescript - protected & static

Cuvely 2023. 4. 18. 10:01
728x90
반응형

Typescript protected

Typescript protected 이란 extends된 클래스에서는 사용이 가능하지만 자식들은 사용이 불가능하다.

class User {
    protected age = 9;	// protected 키워드로 age 변수 선언
}

class NewUser extends User {
    chageAge() {
        this.age = 29;	// extends된 클래스 내에서 age를 사용 할 수 있다.
    }
}

let person = new NewUser();
console.log(person.age); // 자식에서 age를 불러와 사용할 수 없다.

 

 

 

반응형

 

 

 

Typescript static

Typescript static 이란 부모 클래스에 변수가 직접 부여되여서 부모를 통해 사용할 수 있지만 자식은 사용할 수 없다.

class User {
    static age: number = 27;	// static 키워드로 age 변수 선언
    weight: number  = 60;
}

let person = new User();
console.log(person.age);	// 자식인 person 은 age를 사용할 수 없다.
console.log(User.age);		// 부모인 User 클래스는 age를 사용할 수 있다.


console.log(person.weight);	// static이 없는 변수는 자식이 사용할 수 있다.
console.log(User.weight);	// static이 없는 변수는 클래스가 사용할 수 없다.

 

static 키워드는 public, private, protected 키워드에 붙여 사용이 가능하다.

class User {
    private static age: number = 27;	// private 및 static 키워드 속성을 둘다 가지고 있다.
    public static weight: number  = 60;	// public 및 static 키워드 속성을 둘다 가지고 있다.
}

let person = new User();

 

static 키워드는 this를 사용할 수 가 없고 클래스명을 통해 사용할 수 있다.

class User {
    static skill: string = 'js';
    intro: string = '나는 ' + User.skill + ' 전문가 !';	// this가 아닌 클래스를 붙여서 사용한다.

}

let zelord = new User();
console.log(zelord);	// 나는 js 전문가 !

User.skill = 'ts';	// skill을 ts로 변경

let dongdong = new User();	// 새로운 자식을 생성하여 ts를 적용
console.log(dongdong);	// 나는 ts 전문가 !
728x90
반응형