본문 바로가기
JS/JavaScript 강의

[JS] 64. Static Methods in Class

by GiraffePark 2023. 1. 31.

안녕하세요. 박기린 입니다.

 

 

Static Methods

Array.from(), Number.parseFloat()과 같이 프로토타입에서는 쓸 수 없고, Class 원형 그 자체에서만 쓸 수 있는 내장함수들과 같이, 프로토타입으로 상속이 되지 않는 메소드들을 Static Methods라고 부릅니다.

 

+) 프로토타입에 대한 설명이 담긴 글 : https://arnopark.tistory.com/574

 

 

 

 

 


ES6 방식으로 구현하기

+) ES6 Class에 대한 설명이 담긴 글 : https://arnopark.tistory.com/575

 

class PersonCl {
    constructor(fullName, birthYear) {
        this.fullName = fullName;
        this.birthYear = birthYear;
    }
   
    // Static method
    static hey() {
        console.log('Hey there');
        console.log(this);
    }
};

메소드 앞에 static 키워드를 붙임으로써 static method를 구현할 수 있습니다.

 

 

 

 

실행결과물

PersonCl이라는 클래스 이름에 바로 hey() 메소드를 사용합니다. 그러면 정상적으로 작동합니다.

 

 

 

 

 

 

PersonCl에 giraffe라는 인스턴스를 생성합니다.

그리고 giraffe에 static method인 hey()를 사용해봅니다. 그러면 TypeError가 뜨면서 작동하지 않습니다.

이처럼 Static Method는 인스턴스-프로토타입에 상속되지 않고, 원형 그 자체에서만 작동합니다.

 

반응형