정적(static) 프로퍼티와 메서드
static 프로퍼티/메서드
static 프로퍼티/메서드는 생성자 함수나 클래스의 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드를 말한다.
인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다.
생성자 함수에서의 static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 생성자 함수
function Person(name) {
this.name = name
}
// 프로토타입 메서드
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`)
}
// 정적 프로퍼티
Person.staticProp = 'static prop'
// 정적 메서드
Person.staticMethod = function () {
console.log('staticMethod')
}
const me = new Person('Lee')
// 생성자 함수에 추가한 정적 프로퍼티/메서드는 생성자 함수로 참조/호출한다.
Person.staticMethod()
// 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.
// 인스턴스로 참조/호출할 수 있는 프로퍼티/메서드는 프로토타입 체인 상에 존재해야 한다.
me.staticMethod() // TypeError: me.staticMethod is not a function
Person
의 인스턴스인 me
는 자신의 프로토타입 체인에 속한 객체의 프로퍼티와 메서드에 접근할 수 있다.
하지만 정적 프로퍼티/메서드는 인스턴스의 프로토타입 체인에 속하지 않으므로 접근할 수 없다.
클래스에서의 static
클래스에서는 프로퍼티나 메서드에 static 키워드를 붙이면 정적 프로퍼티/메서드가 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person {
//생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name
}
// 정적 메서드
static sayHi() {
console.log('Hi')
}
}
Person.sayHi()
만약 멤버변수에 접근해야 한다면 정적 메서드 대신 프로토타입 메서드를 사용해야 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Square {
constructor(width, hegiht) {
this.width = width
this.hegiht = height
}
area() {
return this.width * this.height
}
}
const square = new Square(10, 10)
console.log(square.area()) // 100
다른 정적 메서드에서의 호출
동일한 클래스 내의 다른 정적 메서드 내에서 정적 메서드를 호출하는 경우 this 키워드를 사용할 수 있다.
1
2
3
4
5
6
7
8
class StaticMethodCall {
static staticMethod() {
return 'Static method has been called'
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method'
}
}
클래스 생성자 및 다른 메서드에서의 호출
비정적 메서드에서는 this 키워드로 정적 메서드에 직접 접근할 수 없다.
클래스명을 사용하여 CLASSNAME.STATIC_METHOD_NAME()
형식으로 호출하거나 동일 클래스 내부인 경우 this.constructor.STATIC_METHOD_NAME()
로 호출할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticMethod())
// 'static method has been called.'
console.log(this.constructor.staticMethod())
// 'static method has been called.'
}
static staticMethod() {
return 'static method has been called.'
}
}
정적 메서드와 프로토타입 메서드의 차이
- 정적 메서드와 프로토타입 메서드는 속해 있는 프로토타입 체인이 다르다. (이미지 참조)
- 정적 메서드는 생성자로 호출하고 프로토타입 메서드는 인스턴스로 호출한다.
- 정적 메서드는 인스턴스 프로퍼티를 참조할 수 없지만 프로토타입 메서드는 인스턴스 프로퍼티를 참조할 수 있다.
static 사용의 장단점 (JAVA 관점 주의)
- 속도가 빨라지고 공유(반복적인 사용)에 효율적이다.
- 같은 메모리 주소를 바라보기 때문에 static 변수를 공유할 수 있다.
- 객체 지향에서 멀어진다.
- 동적 바인딩이 불가능하다.
- 인스턴스마다 프로퍼티를 만드는 게 아니라 메모리 할당을 한번만 할 수 있다.
- 동적 메서드는 가비지 콜렉터 대상이 되지만, static 메소드는 가비지 콜렉터 대상이 아니라 프로그램이 끝날 때까지 메모리를 차지하게 된다.
참고사이트
모던 자바스크립트 Deep Dive
static
정적 메서드와 정적 프로퍼티
정적(static) 변수와 메소드
정적 메소드, 너 써도 될까?
This post is licensed under CC BY 4.0 by the author.