1. JS static 키워드

hchayan·2021년 2월 15일
1

JS 중급이론

목록 보기
1/1
post-thumbnail

1. 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으로 선언된 함수

2. JS 정적 메서드의 특징

정적 메서드는 클래스의 인스턴스 없이 호출이 가능하기에,
보통 유틸리티 함수를 만드는데 사용된다.

// 예제 유틸리티 함수
class Util {
  static generateRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
  }
}

console.log(Util.generateRandomNumber(1, 10))

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

// 클래스 데이터 접근 예제
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

3. static에서의 this 바인딩

위와 같은 이론으로 정적 메서드와 일반 메서드에서 this에 바인딩 되는 내용이 다르다.
this 바인딩에 대한 자세한 내용은 생략.

class Test {
 constructor() {
   this.value = "testValue"
 }

  static staticThis(){
    return this
  }

  normalThis() {
    return this
  }

}

console.log(Test.staticThis(), "\t|\t", Test.staticThis().value)  
// [class Test]  |  undefined

const test = new Test();
console.log(test.normalThis(), "\t|\t", test.normalThis().value)  
// Test { value: 'testValue' }  |  testValue

사전 지식

  • JS 클래스와 인스턴스
  • JS 접근자 프로퍼티(get, set)
  • JS this 바인딩

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/static
https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1

profile
차얀(hchayan)이라는 닉네임을 사용하고 있는 프론트엔드 개발자입니다.

0개의 댓글