protected 키워드
class User{
protected x=10;
}
protected 키워드를 통해 필드 생성
class NewUser extends User{
doThis(){
this.x = 20;
}
}
=> extends로 상속받은 자식까지 필드값을 사용할 수 있게 제한.
this 연산자를 통해 부모의 필드값에 접근할 수 있음.
static 키워드
class User {
x = 10;
y = 20;
}
let john = new User();
john.x //가능
User.x //불가능
static 사용 전
=> 인스턴스 객체로 필드값을 접근할 수 있으나,
클래스. 필드 방법으로는 접근할 수 없음.
class User {
static x = 10;
y = 20;
}
let john = new User();
john.x //불가능
User.x //가능
static 사용 후
=> 인스턴스 객체로 필드값을 접근할 수 없고,
클래스. 필드값으로 접근할 수 있음.
static은 어디에쓰냐
class User {
static skill = 'js';
intro = User.skill + '전문가입니다'
}
User.skill = 'python'; // 가능
var 민수 = new User();
민수.skill = 'python' // 불가능
console.log(민수);
1. 인스턴스 객체가 필드에 접근할 수 없게 할 때 사용.
2. 클래스 객체에 접근하여 필드값을 수정할 수는 있음.
=> 인스턴스 객체를 만들기 전에 접근할 수 있다.
캡슐화 + static
class User {
private static x = 10;
}
public, private, protected와 같은 캡슐화 키워드를 static과 같이 사용할 수 있음.
class User {
private static language = 'js'
intro = User.language + '전문가입니다'
static changeLang(){
User.language = 'ts'
}
}
User.changeLang()
let 철수 = new User();
console.log(철수)
private를 사용하면 더욱 안전하게 외부에서 static일지라도 접근을 하지 못하게 만들 수 있음.
=> 접근을 하려면 클래스 함수를 통해 수정하는 방법뿐임.
이처럼 static 키워드는 함수에도 적용가능.
자바문법이랑 정말 똑같아서 쉽게 다가갈 수 있었다!
하지만 다른 점이 있다면 default 키워드가 따로 없고 기본값은 public으로 설정된다는 점이 포인트다.
그렇지만 constructor (생성자)의 파라미터에는 public으로 설정을 해주어야 접근이 되던데, 이 부분에는 의문점이 생겼다.
'TypeScript' 카테고리의 다른 글
타입을 파라미터로 입력하려면? Generic 문법 (0) | 2023.07.04 |
---|---|
import export, namespace 문법 (0) | 2023.07.04 |
public, private 키워드 (0) | 2023.07.03 |
Narrowing 추가적인 방법들 (0) | 2023.07.03 |
rest parameter , spread operator, destructuring 타입지정 (0) | 2023.07.03 |