정적 속성과 메소드(static properties and methods)
static 키워드를 붙이면 프로퍼티나 메소드가 인스턴스화되지 않고 클래스 자체에 붙는다.
class goodCoder {
static codername = 'noran';
constructor(coderNumber) {
this.coderNumber = coderNumber;
}
static printCoder() {
console.log(goodCoder.codername);
}
}
const coder1 = new goodCoder(1);
const coder2 = new goodCoder(2);
console.log(coder1.codername); //undefined
위 코드에서 console.log(coder1.codername);은 undefined를 뱉는다. codername이 static method이기 때문이다.
그렇기 때문에 console.log(goodCoder.codername);으로 클래스명으로 붙이면 아래 코드처럼 값을 제대로 뱉는다.
console.log(goodCoder.codername); //noran
언제 사용할까?
오브젝트(들어오는 값)에 상관없이 클래스 내에서 공통적으로 쓸 수 있는 것이라면 static을 쓰면 메모리를 효과적으로 줄일 수 있다.
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [mdn, 드림코딩 외] 객체지향 (5) : instanceOf 연산자 (0) | 2022.05.25 |
|---|---|
| [mdn, 드림코딩 외] 객체지향 (4) : 클래스의 상속 (sub classing) (0) | 2022.05.25 |
| [mdn, 드림코딩 외] 객체지향 (2) : 객체(object)와 getter and setter (0) | 2022.05.04 |
| [mdn, 드림코딩 외] 객체지향 (1) : 클래스(class) (0) | 2022.05.03 |
| [드림코딩 외] 콜백함수 (Callback function) (0) | 2022.04.22 |