javascript

[javascript] static 사용하기, class, static method

우주유령 2022. 4. 5. 21:17
728x90
반응형

static method

ES6부터 class가 도입되면서, 클래스 내에서 static method를 사용할 수 있게 되었다. (function에서는 사용할 수 없다)

 

static 키워드를 사용하여 메소드를 정의하면

new "클래스이름" 으로  인스턴스 객체를 생성하지 않아도 해당 메소드를 사용할 수 있다는 장점이 있다.

class A{
	static a(){
    	console.log("a");
    }
}

A.a(); // "a"

 

 

이와 같은 static 메소드는 A자체의 프로퍼티가 된다.

 

 

class대신 function을 사용하면 아래와 같다.

function A() {}
A.a = function(){
	console.log("a");
}
A.a();

 

this.a와 static a

this.a와 static a를 자주 헷갈릴 수 있다.

static a는 A자체의 속성이고, this.a는 A를 통해 생성한 인스턴스의 속성이다.

따라서 new를 통해 A의 인스턴스를 생성하면 static a는 보이지 않는다.

 

class A{
	static a() { console.log(this) } 
    constructor(){
    	this.a = function() {console.log(this)}
    }
}
const a = new A();
console.log(a);

 

 

언제 쓸까?

static 메소드는 new를 통해 인스턴스 객체를 생성하지 않아도 된다는 장점이 있기 때문에

인스턴스마다 해당 메소드를 달아줄 필요가 없는 경우에는 static메소드를 이용하여 많이 구현한다.

실제로 javascript의 메소드들도 그렇게 구현되어있다.

 

Object.keys() 등이 그 예이다.

 

 

 

+ static filed

+ static method는 가능했지만, static field는 정의할 수 없었다. 하지만 클래스 필드가 제안되면서, static field도 같이 제안되었다. 이는 거의 표준이 되기에 확실시되기 때문에 최신브라우저와 node.js에 이미 구현되어있다.

class MyMath{
    static PI = 22/7; // static field
    static #num = 10; // static private
    static increment() { //static method
        return ++MyMath.#num;
    }
}

 

2022.04.05 - [javascript] - [javascript] 클래스 필드란

 

[javascript] 클래스 필드란

java에서는 아래와 같이 사용할 수 있다. public class Person{ priavte String firstName = ""; // 클래스 필드에 클래스 멤버 생성 public String getName() { return this.firstName; } } firstName이 생성된..

wouldyou.tistory.com

2022.04.05 - [javascript] - [javascript] private 정의하기

 

[javascript] private 정의하기

private이 언제부터 가능했지? 원래 javascript는 모두 public이다. 하지만 2021년 1월 TC39의 stage3(candidate)에 private을 정의할 수 있는 새 표준 사양이 제안되었고, 표준 사양으로 승급이 확실시 되기 때문.

wouldyou.tistory.com

 

728x90
반응형