--- title: static slug: Web/JavaScript/Reference/Classes/static tags: - Classes - ECMAScript 2015 - JavaScript - 자바스크립트 - 클래스 translation_of: Web/JavaScript/Reference/Classes/static ---
static 키워드는 클래스의 정적 메서드를 정의합니다.
{{EmbedInteractiveExample("pages/js/classes-static.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
static methodName() { ... }
정적 메서드는 클래스의 인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다. 정적 메서드는 종종 어플리케이션의 유틸리티 함수를 만드는데 사용된다.
동일한 클래스 내의 다른 정적 메서드 내에서 정적 메서드를 호출하는 경우 키워드 this
를 사용할 수 있다.
class StaticMethodCall { static staticMethod() { return 'Static method has been called'; } static anotherStaticMethod() { return this.staticMethod() + ' from another static method'; } } StaticMethodCall.staticMethod(); // 'Static method has been called' StaticMethodCall.anotherStaticMethod(); // 'Static method has been called from another static method'
정적 메서드가 비정적 메서드에서 키워드this
를 써서는 직접적인 접근을 할 수 없다. 바른 호출 방법은 클래스 명칭을 쓰거나, 즉 CLASSNAME.STATIC_METHOD_NAME()
을 이용하거나 혹은 그 메서드를 생성자의 한 속성으로 부르는 것으로, 즉 constructor
: this.constructor.STATIC_METHOD_NAME()
를 이용한다.
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.'; } }
아래 예제는 여러가지 내용을 설명합니다.
class Triple { static triple(n) { n = n || 1; //비트연산이 아니어야 합니다. return n * 3; } } class BiggerTriple extends Triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(Triple.triple()); // 3 console.log(Triple.triple(6)); // 18 console.log(BiggerTriple.triple(3)); // 81 var tp = new Triple(); console.log(BiggerTriple.triple(3)); // 81 (부모의 인스턴스에 영향을 받지 않습니다.) console.log(tp.triple()); // 'tp.triple은 함수가 아닙니다.'. console.log(tp.constructor.triple(4)); // 12
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}} | {{Spec2('ES6')}} | Initial definition. |
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.classes.static")}}