정적 메서드 static method 란?
prototype
이 아닌 클래스 함수 자체의 메서드를 말한다.
정적 메서드는 클래스의 인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다.
정적 메서드는 종종 어플리케이션의 유틸리티 함수를 만드는데 사용된다.
정적 메서드의 호출
다른 정적 메서드의 호출
동일한 클래스 내의 다른 정적 메서드 내에서 정적 메서드를 호출하는 경우, 키워드 this
를 사용할 수 있다.
class StaticMethodCall {
static staticMethod() {
return "Static method has been called";
}
static anotherStaticMethod() {
return this.staticMethod() + " from another static method";
}
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'
클래스 생성자 및 다른 메서드에서의 호출
클래스의 명칭을 쓰거나, 그 메서드를 생성자의 한 속성으로 부르는 것으로, 즉 constructor
를 이용한다.
정적 메서드가 비정적 메서드에서 키워드 this
를 써서 직접적인 접근을 할 수 없다.
class Triple {
static triple(n) {
n = n || 1; //비트연산이 아니어야 합니다.
return n * 3;
}
}
class BiggerTriple extends Triple {
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
console.log(Triple.triple()); // 3
console.log(Triple.triple(6)); // 18
console.log(BiggerTriple.triple(3)); // 81
var tp = new Triple();
console.log(BiggerTriple.triple(3)); // 81 (부모의 인스턴스에 영향을 받지 않습니다.)
console.log(tp.triple()); // 'tp.triple은 함수가 아닙니다.'.
console.log(tp.constructor.triple(4)); // 12
정적 프로퍼티 static property 란?
정적 프로퍼티는 일반 클래스 프로퍼티와 유사하게 생겼는데 static
이 붙는다는 점만 다르다.
class Article {
static publisher = "Ilya Kantor"
}
// Article.publisher = "Ilya Kantor"처럼 직접 할당하는 것과 동일하게 작용
console.log(Article.publisher) //"Ilya Kantor"
정적 메서드와 프로퍼티 상속
정적 메서드와 정적 프로퍼티는 상속된다.
class Animal {}
class Rabbit extends Animal {}
// 정적 메서드
alert(Rabbit.__proto__ === Animal); // true
// 일반 메서드
alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
static 을 사용하는 이유
복제가 필요없는 데이터를 다루기에 효과적이다.
class App {
static init() {
console.log("static init called");
}
}
const appInstance = new App(); //App 인스턴스 생성
console.log(appInstance.init()); // error Uncaught TypeError: appInstance.init is not a function
App.init(); //static init called
위의 코드처럼, 코드에서 한 번만 사용되는데 인스턴스를 생성하면 추가적인 데이터 공간이 낭비되기도 하고, 코드 길이가 길어진다.
`static`을 사용하면 인스턴스를 따로 만들지 않고 메서드를 실행할 수 있다.
요약
1. 정적 메서드는 특정 클래스가 아닌 전체에 필요한 기능을 만들 때 사용할 수 있다.
2. 정적 프로퍼티는 데이터를 클래스 수준에 저장하고 싶을 때 사용한다. 정적 프로퍼티 역시 개별 인스턴스에 묶이지 않는다.
3. static을 사용하면 기술적으로는 클래스 자체에 할당하는 것과 동일하다.
4. 클래스의 인스턴스에서 호출될 수 없고, 클래스 자체에서 호출될 수 있다.
5. 정적 메서드와 프로퍼티는 상속이 가능하다.
참조
https://ko.javascript.info/static-properties-methods
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/static
'FrontEnd > JavaScript' 카테고리의 다른 글
[ JavaScript ] 배열에서 특정 요소 찾기 (0) | 2023.11.13 |
---|---|
[ JavaScript ] 문자열에서 공백 있는지 확인하기 (0) | 2023.11.04 |
[ JavaScript ] 현재 시간 가져오기 (feat. Date) (0) | 2023.11.02 |
[ JavaScript ] splice() vs slice() (0) | 2023.11.02 |
[ JavaScript ] every() (0) | 2023.11.01 |