class Experiment {
publicFied = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicFied);
console.log(experiment.privateField);
constructor(생성자)
를 쓰지 않고, 필드를 정의할 수 있는데,
publicFied = 2;
처럼 그냥 정의하게 되면 Public
필드가 되어 외부에서 접근이 가능하지만
privateField = 0;
처럼 #해시기호
를 붙이게 되면 Private
필드가 되어 클래스 내부
에서만 값이 보여지고 접근이 되고 값을 변경할 수 있다. 즉, 외부에서는 접근 및 값 변경이 불가능하다.
console.log(experiment.publicFied); // 2
console.log(experiment.privateField); // undefined
그래서 publicFied
는 2
라는 값이 출력되지만 privateField
는 undefined
가 출력된다.
class Article {
static publisher = 'summer Lee';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
class
안에 있는 필드
와 메소드
들은 새로운 object
를 만들때 마다 그대로 복제되어 값만 우리가 지정한 값으로 변경이 되어 만들어진다.
간혹, obeject
즉 데이터
에 상관 없이 클래스가 가지고 있는 고유한 값과, 동일하게 반복적으로 사용되어지는메소드
가 있을 수 있다.
그런 것들을 static
이라는 키워드를 이용하여 붙이면, object
에 상관 없이 클래스 자체에 연결 되어 있다.
이게 무슨 뜻이냐하면, 아래와 같다.
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); // undefined
이렇게 article1, articel2
라는 오브젝트를 만들었을때 만약 우리가 static
을 사용하지 않았다면
console.log(article1.publisher);
처럼 작성했을 때, article1
의 publisher
를 출력할 수 있었을 것이다.
하지만 static
을 사용한다면 undefined
가 출력될 것이다. 이는, 오브젝트(article1
) 안에 publisher
라는 값을 읽을 수 없기 때문에 나타난다.
왜냐하면 static
은 오브젝트마다 할당 되어지는 것이 아니라 Article
이라는 클래스 자체
에 붙어있는 것이기 때문이다.
그래서
console.log(Article.publisher); // summer Lee
처럼 클래스 자체를 콘솔로그로 찍게 되면 정상적으로 값이 출력되는 것을 볼 수 있다.
static
함수를 호출할 때 클래스 이름
을 이용해서
Article.printPublisher(); // summer Lee
라고 호출하면 값이 정상적으로 출력되는 것을 볼 수 있다.
오브젝트 & 들어오는 데이터에 상관 없이 공통적으로 클래스에서 쓸 수 있는 거라면 static
과 static method
를 이용해서 작성하는 것이 메모리의 사용을 조금 더 줄일 수 있다.