인스턴스를 만들지 않고 클래스에서 바로 사용할 수 있는 속성과 메소드 인스턴스에서는 접근할 수 없다.
class 클래스 이름 {
static 속성 = 값
static 메소드 () {
}
}
클래스 이름.속성
클래스 이름.메소드()
예시
class Square {
#length;
static #conuter = 0;
static get counter() {
return Square.#conuter;
}
constructor(length) {
this.length = length;
Square.#conuter += 1; <<<< Square의 생성자를 호출할 때마다 counter 1씩 증가
} <<<< Square 객채를 통해 몇 개의 인스턴스를 만들었는지 알 수 있다.
static perimeterOf(length) { <<<< static 속성으로 함수를 만들어 인스턴스 만들지 않고 바로 둘레/넓이 구할 수 있게 함
return length * 4;
}
static areaOf(length) { <<<< static 속성으로 함수를 만들어 인스턴스 만들지 않고 바로 둘레/넓이 구할 수 있게 함
return length * length;
}
get length() {
return this.#length;
}
get perimeter() {
return this.#length * 4;
}
get area() {
return this.#length * this.#length;
}
set length(length) {
if (length < 10) {
throw '길이는 0보다 커야 합니다.';
}
this.#length = length;
}
}
// static 속성 사용하기
const squareA = new Square(10);
const squareB = new Square(20);
const squareC = new Square(30);
static 메소드 사용하기
console.log(`지금까지 생성된 Square 인스턴스는 ${Square.counter}개입니다.`);
지금까지 생성된 Square 인스턴스는 3개입니다.
console.log(`한 변의 길이가 20인 정사각형의 둘레는 ${Square.perimeterOf(20)}입니다.`);
한 변의 길이가 20인 정사각형의 둘레는 80입니다.
console.log(`한 변의 길이가 30인 정사각형의 넓이는 ${Square.areaOf(30)}입니다.`);}
한 변의 길이가 30인 정사각형의 넓이는 900입니다.
인스턴스에서..
console.log(squareA.perimeter); // 40
console.log(squareA.area); // 100
console.log(squareA.length); // 10
console.log(squareA.counter); // undefined
console.log(squareA.perimeterOf(20));
// TypeError: squareA.perimeterOf is not a function