본문 바로가기
JavaScript

JavaScript 기초(29)_클래스(4) static

by DeBanker.K 2021. 10. 26.

1. static 변수, 함수 

: 객체가 아닌, 클래스의 변수와 함수 

 

다음의 코드를 보자.

class A {
    static age = 31;
    static hello(){
        console.log(A.age);
    }
}

console.log(A);
console.log(A.age);
A.hello();
[Running]
[class A] { age: 31 }
31
31

클래스 A를 출력했을 때, [] 안에 클래스 이름이 나오며 {} 안에는 변수와 값이 출력된다.

A.age로 접근하여 출력했을 때도 31이 정상 출력되며

A.hello()로 hello() 함수에 접근하여도 31이 정상 출력된다. 

 

그렇다면 위 코드에서 'static'을 제거하면 어떻게 될까?

class B {
    age = 31;
    hello(){
        console.log(A.age);
    }
}

console.log(B);
console.log(B.age);
B.hello();
[Running]
[class B]
undefined
B.hello();
  ^
TypeError: B.hello is not a function

클래스 B를 출력했을 때, []안에 클래스 이름은 나오지만 age 값은 표기되지 않는다.

B.age로 접근했을 때도 인식하지 못하여 'undefined'로 출력되며

B.hello()로 hello() 함수에 접근해도 타입 애러를 일으킨다. 

 

즉, static 변수와 함수 = 클래스의 변수와 함수라고 볼 수 있겠다.

 

class C {
    static name = '이 클래스의 이름은 C가 아니다'
}

console.log(C);
[Running]
[class 이 클래스의 이름은 C가 아니다] { name: '이 클래스의 이름은 C가 아니다' }

재밌는 것(?)이 하나 있는데 위와 같이 static name 변수에 할당된 값이 

그대로 class 이름으로 출력된다는 것인다.

 

class C {
    static name1 = '이 클래스의 이름은 C가 아니다'
}

console.log(C);
[Running]
[class C] { name1: '이 클래스의 이름은 C가 아니다' }

static name 이외의 다른 것들은 클래스 이름으로 나타낼 수가 없다. 

위와 같이 'class C'로 나온다. 

 

 

댓글