자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Javascript] New Javascript 12장 정적 메서드/필드

728x90

✅ 1. 정적 메서드 (Static Method)

정적 메서드(Static Method)는 클래스 자체에서 호출되는 함수로, 인스턴스 없이 클래스 이름으로 직접 사용합니다. 유틸리티 함수나 공용 기능에 자주 사용되는 메서드입니다.

class MathUtil {
  static randomInt(min, max) {
    // 정적 메서드
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

console.log(MathUtil.randomInt(1, 20)); // ✅ 1~20 사이의 랜덤 정수

✅ 2. 정적 필드 (Static Field) 

정적 필드(Static Field)는 클래스 자체에 속하는 함수로, 인스턴스가 아닌 클래스에 바로 접근합니다. 보통 공유 데이터나 상수(변하지 않는 값)를 지정할 때 사용합니다.

class Circle {
  static pl = 3.14159; // 정적 필드

  constructor(radius) {
    this.radius = radius; // 인스턴스 필드 선언
  }

  area() {
    return Circle.pl * this.radius ** 2; // 클래스 이름으로 접근
  }
}

console.log(Circle.pl); // ✅ 3.14159
const c = new Circle(15);
console.log(c.area()); // ✅ 706.85775
// console.log(c.pl); // ❌ undefined, 인스턴스에서는 접근 불가

✅ 3. 두 가지 특징 

정적 메서드(Static Method)와 정적 필드(Static Field)의 특징은 인스턴스 생성 없이 사용이 가능하고 클래스 단위로 공유합니다. 이로 인해 모든 인스턴스가 같은 값을 참조해 프라이빗과도 결합이 가능합니다.

class Example {
  static #secret = "hidden";

  static getSecret() {
    return Example.#secret;
  }
}

console.log(Example.getSecret()); // Outputs: 'hidden'

 

 

GitHub - javascript-only/newJSRoom: https://thinky.tistory.com/category/Front-End/JavaScript

https://thinky.tistory.com/category/Front-End/JavaScript - javascript-only/newJSRoom

github.com

 

728x90
LIST