
class 접근 제한자를 알아보기전에 class에 대해 간단하게 알아보자.
class: es6에 새롭게 도입된 클래스는 기존 프로토 타입 기반 객체지향 언어보다 클래스 기반 언어에 익숙한 개발자가 빠르게 학습할 수 있는 단순명료한 새로운 문법을 제시하고 있다. 하지만 클래스가 새로운 객체지향 모델을 제공하는 것은 아니다. 사실 클래스도 함수이고 기존 프로토타입 기반 패턴의 syntactic sugar일 뿐이다. TypeScript가 지원하는 클래스는 es6클래스와 상당히 유사하지만 몇 가지 TypeScript만의 고유한 확장 기능이 있다.
es6클래스는 클래스 몸체에 메소드만을 포함할 수 있다. 클래스 몸체에 클래스 프로퍼티를 선언할 수 없고 반드시 생성자 내부에서 클래스 프로퍼티를 선언하고 초기화한다.
class User{
constructor(name){
// 클래스 프로퍼티 선언과 초기화
this.name = name;
}
students(){
console.log(`${this.name} is student.`);
}
}
위 코드는 es6에서 문제없지만 ts로 변경할 시 컴파일하면 컴파일에러가 발생한다.
TypeScript 클래스는 클래스 몸체에 클래스 프로퍼티를 사전 선언해야한다.
class User{
name:string;
constructor(name){
// 클래스 프로퍼티 선언과 초기화
this.name = name;
}
students(){
console.log(`${this.name} is student.`);
}
}
const school = new User('철수');
school. students // output: '철수 is student.'
❗public / readonly를 사용해주면 member변수를 미리 선언하지 않아도 된다.
접근 가능성 public protected private 클래스 내부 ◯ ◯ ◯ 자식클래스 내부 ◯ ◯ X 클래스 인스턴스 ◯ X X
// private을 붙이면 class{}안에서만 사용가능
// protected을 붙이면 현재 class{}안에서 + extends된 class{}안에서 사용가능
class User {
protected x=10;
}
class NewUser extends User {
doThis(){
this.x=20;
}
}
let 사람 = new NewUser()
console.log(사람)

class Foo {
public x : string;
protected y : string;
private z : string;
constructor(x:string,y:string,z:string) {
// public,protected,private **모두 클래스 내부에서 참고 가능.**
this.x=x;
this.y=y;
this.z=z;
}
}
// 클래스 인스턴스를 통해 클래스 외부 참조
const foo = new Foo('x','y','z');
console.log(foo.x); // 참조 가능
console.log(foo.y); // 참조 불가능
console.log(foo.z); // 참조 불가능
// 자식 클래스 내부에 참조
class Bar extends Foo {
constructor(x:string,y:string,z:string) {
super(x,y,z);
console.log(this.x); // 참조 가능
console.log(this.y); // 참조 가능
console.log(this.z); // 참조 불가능
class Foo {
// public으로 x는 클래스 외부에서도 참조가 가능하다.
constructor(public x:string) {}
}
const foo = new Foo('Hello');
console.log(foo); // Foo {x:'Hellow'}
console.log(foo.x); // Hello
class Bar {
// private으로 클래스 내부에서만 참조 가능하다.
constructor(private x:string) {}
}
const bar = new Bar('Hello');
console.log(bar); // Bar {x:'Hello'}
console.log(bar.x); // 참조 불가
this가 아닌 클래스명으로만 접근이 가능하다.class Age{
static a = 10;
b=11;
}
let 자식 = new Age()
console.log(자식) // b만 콘솔에서확인가능
class Foo {
static instanceCounter = 0;
constructor() {
// 생성자가 호출될 때마다 카운터를 1씩 증가시킨다.
Foo.instanceCounter++;
}
}
var foo1 = new Foo();
var foo2 = new Foo();
console.log(Foo.instanceCounter); //2
console.log(foo2.instanceCounter); // error
class Person{
static skill='js';
// this.skill불가 부모만이올수있음
intro=Person.skill+'전문가입니다';
}
let 짱구 = new Person()
console.log("짱구: ",짱구.intro) // 짱구: js전문가입니다
Person.skill='ts';
let 유리 = new Person()
console.log("유리: ",유리.intro) // 유리: ts전문가입니다
[Typescript] 클래스(Class) : private, protected, public
12.4 TypeScript - Class