TypeScript

[TypeScript]static property, static method

DevStory 2022. 3. 24.

정적 변수와 정적 함수

static 키워드를 사용하여 선언된 변수와 함수는 정적 변수, 정적 함수라고 말합니다. 정적 변수와 정적 함수는 클래스에 속하는 변수와 함수로 변수와 함수를 호출하기 위해 객체가 필요하지 않습니다. 클래스에서 바로 호출할 수 있습니다.

 

일반적으로 클래스의 변수와 함수를 접근하기 위해서는 다음과 같이 객체를 생성해야 합니다.

class ClassExample {
  private _field: string;
  
  get field() {
    return this._field;
  }

  set field(theField: string) {
    this._field = theField;
  }
  
  public printField() {
    console.log('field: ' + this._field);
  }
}

// 객체 생성
var classExample1 = new ClassExample();

// ClassExample 클래스의 필드 값 설정
classExample1.field = "hi";

// ClassExample 클래스의 함수 호출
classExample1.printField();
// hi

// 객체 생성
var classExample2 = new ClassExample();

// ClassExample 클래스의 필드 값 설정
classExample2.field = "hello";

// ClassExample 클래스의 함수 호출
classExample2.printField();
// hello

위 코드에서 _field 변수는 classExample1, classExample2 객체 인스턴스에 존재하며 객체별로 값이 관리됩니다.

 

하지만, 정적 변수, 정적 함수는 클래스 자체에 속하기 때문에 객체가 아닌 클래스에서 직접 호출해야 하며 객체마다 영향을 줄 수 있습니다.

반응형

정적 변수와 정적 함수 정의

정적 변수를 정의하려면 변수명 앞에 static 키워드를 추가합니다. 객체를 생성하지 않고 점 표기법을 사용하여 클래스에서 직접 호출할 수 있습니다.

class ClassExample {
  public static _field:string = "Hello";
}

console.log(ClassExample._field);
// Hello

 

정적 함수를 정의하려면 함수명 앞에 static 키워드를 추가합니다. 호출 방법은 정적 변수와 동일합니다.

class ClassExample {
  public static printField() {
    console.log('printField() call');
  }
}

ClassExample.printField();
// printField() call

정적 함수에서 정적 변수의 값 변경

정적 함수는 정적 변수의 값을 변경할 수 있습니다.

class ClassExample {
  public static count: number = 0;

  public static setCount() {
    this.count += 1;
    console.log(`count: ${this.count}`)
  } 
}

ClassExample.setCount(); // count: 1
ClassExample.setCount(); // count: 2
ClassExample.setCount(); // count: 3

정적 함수에서 정적 변수의 값을 변경하는 것은 가능하지만, 정적 함수에서 일반 변수(static 키워드가 없는 변수)의 값을 변경하는 것은 불가능합니다.

class ClassExample {
  public count: number = 0;

  public static setCount() {
    this.count += 1;
    console.log(`count: ${this.count}`)
  } 
}

TypeScript에서 다음 오류를 확인할 수 있습니다.

count는 인스턴스 속성이므로 객체에 속합니다. 반드시 객체를 생성 후 객체에서 값을 변경해야 합니다.

 

그리고 객체에서 정적 변수와 정적 함수 호출하는 경우 다음과 같이 오류가 발생합니다.

class ClassExample {
  public static count: number = 0;

  public static setCount() {
    this.count += 1;
    console.log(`count: ${this.count}`)
  } 
}

var classExample1 = new ClassExample();
classExample1.setCount();

다음 오류를 확인할 수 있습니다.

TypeScript는 정적 변수 또는 정적 함수가 객체 인스턴스의 영향받는 것을 허용하지 않기 때문입니다.


정리

이번 포스팅에서는 TypeScript의 정적 변수와 정적 함수에 대해 알아보았습니다.

  • 정적 속성과 정적 함수는 static 키워드를 사용하여 정의합니다.
  • 객체를 생성하지 않고 정적 변수와 정적 함수를 호출할 수 있습니다.
  • 객체에서 정적 변수와 정적 함수를 호출할 수 없습니다.
반응형

댓글