[JavaScript] Static

최승원·2022년 2월 8일
0

TIL (Today I Learned)

목록 보기
7/21

Static이란

Static은 클래스의 정적 메서드(클래스의 종속적인 메서드)를 의미한다.
클래스와 해당 메서드는 연결되어 있지만, 해당 클래스의 특정 인스턴스와는 연결되어있지 않다.
그래서 정적메서드는 특정 객체(클래스)에 저장된 데이터에 접근할 수 없다.

// static을 사용한 변수, 함수 선언 및 사용 방식
class Test {

  static staticVariable = "static 변수";
  static staticFunction() {
    return "static 메서드"
  }
  
}

// const test = new Test(); // 정적 메서드는 클래스의 호출 없이 사용이 가능하다. 따라서 생략 가능.
console.log(Test.staticVariable) // 출력 : static 변수
console.log(Test.staticFunction()) // 출력 : static 메서드

Static의 특징

정적 메서드는 클래스의 데이터를 가져오지 못하고, 객체의 인스턴스를 생성해도 정적 메서드는 클래스의 데이터를 가져오지 못한다.

// 클래스 데이터 접근 예제
class Person {
  constructor() {
    this._name = "KIM";
  }

  static get name(){
    return this._name
  }

}


// 1. 정적 메서드를 이용해 클래스 데이터 가져오기 - 실패
console.log(Person.name)  // undefined

// 2. 클래스 인스턴스를 선언해 클래스 데이터 가져오기 - 실패
const person = new Person();
console.log(person.name)  // undefined

참고

1. JS static 키워드

profile
문의 사항은 메일로 부탁드립니다🙇‍♀️

0개의 댓글