ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • static과 is not a function
    자바스크립트/기본문법 2023. 11. 7. 05:28

    정적 메서드

    class Counter {
      constructor(){this.cc = "cc"}
      static count = 0;
      static increment() { Counter.count++; }
      static getCount() { return Counter.count; }
    }
    
    Counter.increment();
    console.log(Counter); 
    let c = new Counter();
    console.log(c);

    static으로 선언된 변수와 메서드는 클래스로만 접근 가능하며

    해당 클래스로 생성된 인스턴스는 이에 접근할 수 없다.

    -> c라는 인스턴스를 출력시 static 변수 count는 출력되지 않는다.

     

    import input from './userInput.js'
    
    class App {
      async play() {
        const purchaseAmount = await input.inputPurchaseAmount();
      }
    }
    
    export default App;
    export default class input  {
      static async inputPurchaseAmount() {
        let purchaseAmount = Console.readLineAsync("구입금액을 입력해 주세요.\n"));
        return purchaseAmount;
        }
    }

    이와 같이 static으로 지정된 메서드는 별도의 인스턴스 생성 없이 바로 사용가능하다.

     

     

     

     

    또한 반대로 클래스는 static이 아닌 변수/메서드에 접근 불가능하다.

     

    static = 클래스 전용

    그 외 = 메서드 전용

     

    is not a funcion 에러가 떠서 뭔가 고민했는데

    static을 지정 안해서였다 ;ㅅ;

     

     

     

    class MyClass {
      static staticMethod() {
        console.log('This is a static method');
        console.log(this); // 'this' refers to the class itself
      }
    
      instanceMethod() {
        console.log('This is an instance method');
        console.log(this); // 'this' refers to an instance of the class
      }
    }
    
    const myInstance = new MyClass();
    MyClass.staticMethod(); // This is a static method
    myInstance.instanceMethod(); // This is an instance method

    static 메서드의 this는 클래스를,

    그 외 메세드의 this는 인스턴스를 가리키니 주의

    '자바스크립트 > 기본문법' 카테고리의 다른 글

    에러 & 출력 문구 상수화  (1) 2023.11.07
    자바스크립트 Set  (0) 2023.08.12
    Map - 배열과 이터레이터  (0) 2023.08.12
    자바스크립트 함수  (0) 2023.08.10
    ES6 문법 정리  (0) 2023.08.07
Designed by Tistory.