정적(static) 메서드
prototype 이 아닌 클래스 함수 자체에 메서드를 설정한 것을 static 메서드 라고 함
class MyClass{
static staticMethod(){}
method(){}
}
console.dir(MyClass);
결과
위의 MyClass 의 구조를 보면 static 키워드를 사용한 staticMethod는 MyClass에 바로 설정되어 있고 사용하지 않는 method 는 prototype 내부에 설정되어 있는것을 볼 수 있음
정적(static) 메서드의 사용
정적 메서드는 클래스 함수에 직접 할당되어 있으므로 new 를 이용하여 객체를 생성하지 않아도 실행 될 수 있음
//정적 메서드를 이용하여 객체를 생성
class Person{
constructor(name,age,born){
this.name = name;
this.age = age;
this.born = born;
}
static makePerson(name,born){
let age = new Date().getFullYear() - born.getFullYear();
//자기자신, 즉 Person을 생성
return new this(name,age,born);
}
}
let person1 = Person.makePerson('lee',new Date(1993,02,07));
console.dir(person1);
결과
직접 new 연산으로 객체를 생성하지 않고 정적 메서드를 이용하여 객체를 생성할 수 있음
정적 프로퍼티
정적 프로퍼티도 프로퍼티 앞에 static을 명시해 주어서 사용할 수 있음
class MyClass{
//정적 프로퍼티
static num = 10;
//일반 프로퍼티
num2 = 11;
}
//이 방식도 정적 프로퍼티를 정의한 것
MyClass.str = 'static property';
정적 메서드와 정적 프로퍼티 역시 상속됨
class Person{
//정적 프로퍼티와 메서드를 추가
static firstName = 'lee'
static getStaticName(){
return this.firstName;
}
}
//Person을 상속
class Student extends Person {}
console.log(Student.getStaticName());
결과
참조: https://ko.javascript.info/static-properties-methods
'JavaScript > JavaScript기초' 카테고리의 다른 글
[Javascript] Javascript 내장 클래스 확장 (0) | 2021.10.18 |
---|---|
[Javascript] private, protected (0) | 2021.10.14 |
[Javascript] 클래스 상속 (0) | 2021.10.01 |
[Javascript] 클래스 (0) | 2021.09.30 |
[Javascript] 프로토타입 메서드 (0) | 2021.09.30 |