class User {
public name: string;
constructor() {
this.name = 'kim';
}
}
let 유저1 = new User();
유저1.name = 'park'; // 가능
class User {
public name: string;
private familyName: string;
constructor() {
this.name = 'kim';
let hello = this.familyName + '안뇽'; // 가능 (클래스 내부)
}
}
let 유저1 = new User();
유저1.name = 'park'; // 가능
유저1.familyName = '456'; // 에러 (외부 접근 불가)
외부에서 private 속성을 수정하려면 클래스 내부에 함수를 만들어 간접 접근
class User {
private familyName: string;
changeSecret() {
this.familyName = 'park'; // 클래스 내부에서 수정
}
}
let 유저1 = new User();
유저1.changeSecret(); // 함수를 통한 간접 수정
활용법: 중요한 데이터를 실수로 수정하는 것을 방지하고, 안전장치를 추가한 개발 가능
public/private 키워드를 constructor 파라미터에 붙이면 필드 선언과 할당을 동시에 처리
// 기존 방식
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
// 단축 문법
class Person {
constructor(public name: string) {
// this.name = name 자동 생성
}
}
private와 비슷하지만 extends로 상속받은 클래스에서도 사용 가능
class User {
protected x = 10;
}
class NewUser extends User {
doThis() {
this.x = 20; // protected라서 가능 (private이면 에러)
}
}
속성이나 메서드를 클래스 자체에 부여 (인스턴스가 아닌)
class User {
static x = 10; // 클래스에 직접 부여
y = 20; // 인스턴스에 부여
}
let john = new User();
john.x; // 불가능
User.x; // 가능 (10)
john.y; // 가능 (20)
클래스의 기본 설정값이나 공통 데이터 저장용
class User {
static skill = 'js';
intro = User.skill + ' 전문가입니다';
}
// 설정 변경
User.skill = 'python';
let 민수 = new User(); // 'python 전문가입니다'
class User {
private static x = 10; // 클래스 내부에서만 접근 가능한 static
public static y = 20; // 어디서든 접근 가능한 static
protected z = 30; // 상속 클래스에서도 사용 가능
}
class User {
private static x = 10; // User 클래스에서만 접근, 수정 가능
public static y = 20; // 어디서든 User.y로 접근, 수정 가능
protected z = 30; // 클래스 내부 + 상속 클래스에서 사용 가능
}
class User {
private static x = 10;
public static y = 20;
static addOne(param: number) {
User.x += param; // static 속성은 클래스명.속성으로 접근
}
static printX() {
console.log(User.x);
}
}
User.addOne(3);
User.printX(); // 13
class Square {
constructor(
public width: number,
public height: number,
public color: string
) {}
draw() {
let randomPos = Math.random() * 400; // 0~400px 랜덤 위치
let square = `<div style="
position: relative;
top: ${randomPos}px;
left: ${randomPos}px;
width: ${this.width}px;
height: ${this.height}px;
background: ${this.color}
"></div>`;
document.body.insertAdjacentHTML('beforeend', square);
}
}
let 네모 = new Square(30, 30, 'red');
네모.draw(); // 랜덤 위치에 빨간 사각형 생성
| 키워드 | 접근 범위 | 설명 |
|---|---|---|
| public | 어디서든 | 기본값, 자유롭게 접근 가능 |
| private | 클래스 내부만 | 외부 접근 차단, 보안성 높음 |
| protected | 클래스 + 상속 클래스 | private보다 범위가 넓음 |
| static | 클래스 자체 | 인스턴스가 아닌 클래스에 직접 부여 |
핵심: 각 키워드는 데이터 보안과 코드 구조화를 위한 도구들입니다