CodeGym /행동 /Frontend SELF KO /정적 메소드

정적 메소드

Frontend SELF KO
레벨 40 , 레슨 1
사용 가능

8.1 정적 메소드 선언

JavaScript의 정적 메소드는 인스턴스가 아닌 클래스 자체에서 정의되는 메소드야. 이 메소드는 클래스에서 직접 호출되고, 이 클래스로 생성된 객체에서는 호출되지 않아. 정적 메소드는 클래스와 관련이 있는 도움이 되는 함수들을 만들 때 자주 사용돼.

정적 메소드는 클래스 본문에서 메소드 정의 앞에 static 키워드를 사용해서 선언돼.

예제:

  • addmultiply 메소드는 static 키워드를 사용하여 정적으로 선언됨
  • 이 메소드는 MathHelper 클래스에 직접 호출되며, 그 인스턴스에 호출되지 않아
JavaScript
    
      class MathHelper {
        static add(a, b) {
          return a + b;
        }

        static multiply(a, b) {
          return a * b;
        }
      }

      console.log(MathHelper.add(5, 3)); // 8
      console.log(MathHelper.multiply(5, 3)); // 15
    
  

8.2 정적 메소드 사용

정적 메소드는 다음과 같은 경우에 유용해:

  1. 도움이 되는 함수: 정적 메소드는 클래스와 관련된 작업을 수행하는 유틸리티 함수를 작성하는 데 사용될 수 있어.
  2. 팩토리 메소드: 정적 메소드는 특정 로직을 가지고 클래스의 인스턴스를 만들 때 사용할 수 있어.
  3. 데이터 처리: 클래스와 관련된 데이터를 처리하는 데 사용될 수 있지만, 인스턴스 생성이 필요하지 않을 때.

도움이 되는 함수의 예시:

  • StringUtil 클래스에는 문자열을 다루는 정적 메소드 capitalizereverse가 포함돼 있어
  • 이 메소드는 StringUtil 클래스에 직접 호출돼
JavaScript
    
      class StringUtil {
        static capitalize(str) {
          return str.charAt(0).toUpperCase() + str.slice(1);
        }

        static reverse(str) {
          return str.split('').reverse().join('');
        }
      }

      console.log(StringUtil.capitalize('hello')); // "Hello"
      console.log(StringUtil.reverse('hello')); // "olleh"
    
  

팩토리 메소드의 예:

정적 메소드 fromObject는 데이터 객체에서 Car 클래스의 인스턴스를 생성해.

JavaScript
    
      class Car {
        constructor(brand, model) {
          this.brand = brand;
          this.model = model;
        }

        static fromObject(obj) {
          return new Car(obj.brand, obj.model);
        }
      }

      const carData = { brand: 'Toyota', model: 'Camry' };
      const car = Car.fromObject(carData);

      console.log(car.brand); // "Toyota"
      console.log(car.model); // "Camry"
    
  

8.3 정적 메소드와 상속

JavaScript에서 정적 메소드는 파생 클래스에 상속돼. 이 클래스들은 기본 클래스의 정적 메소드를 사용하거나 재정의할 수 있어.

정적 메소드 상속의 예:

  • identify 정적 메소드는 Animal 클래스에 정의돼 있고 Dog 클래스에서 재정의돼
  • 두 클래스에서 identify 메소드를 호출해
JavaScript
    
      class Animal {
        static identify() {
          return 'This is an animal';
        }
      }

      class Dog extends Animal {
        static identify() {
          return 'This is a dog';
        }
      }

      console.log(Animal.identify()); // "This is an animal"
      console.log(Dog.identify()); // "This is a dog"
    
  

8.4 다른 메소드 내에서 정적 메소드 접근

정적 메소드는 클래스 이름을 사용하여 다른 메소드 내에서 호출될 수 있어.

예제:

정적 메소드 calculateArea는 다른 정적 메소드 describeCircle 내에서 this 키워드를 사용하여 호출되며, 이는 이 컨텍스트에서 Geometry 클래스를 참조해.

JavaScript
    
      class Geometry {
        static calculateArea(radius) {
          return Math.PI * radius * radius;
        }

        static describeCircle(radius) {
          const area = this.calculateArea(radius);
          return `A circle with radius ${radius} has an area of ${area.toFixed(2)}.`;
        }
      }

      console.log(Geometry.describeCircle(5)); // "A circle with radius 5 has an area of 78.54."
    
  

8.5 정적 메소드와 클래스 인스턴스

정적 메소드는 클래스의 인스턴스에서 호출될 수 없어. 인스턴스에서 정적 메소드를 호출하려고 하면 오류가 발생해.

예제:

정적 메소드 addCalculator 클래스에 호출되고, 그 인스턴스 calc에 호출되지 않아.

JavaScript
    
      class Calculator {
        static add(a, b) {
          return a + b;
        }
      }

      const calc = new Calculator();
      console.log(Calculator.add(3, 4)); // 7

      console.log(calc.add(3, 4)); // 오류: calc.add는 함수가 아님
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION