This translation is incomplete. Please help translate this article from English.

Cuvantul cheie static defineste o metoda statica a unei clase.

Sintaxa

static methodName() { ... }

Descriere

Invocarile metodei static sunt facute direct asupra unei clase si nu sunt invocate asupra unei instante a clasei. Metodele static sunt deobicei folosite in a crea functii utilitare.

Invocarea metodei static

 

Din alte metode statice

Pentru a putea invoca o metoda static intr-o alta metoda static a aceleasi clase se va folosi 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'

Din constructor si alte metode

Metodele static nu sunt direct accesibile folosind this din metode non-static. Este nevoie sa se foloseasca clasa: CLASSNAME.STATIC_METHOD_NAME() sau prin invocarea metodei ca si propietate a constructorului 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.';
  }
}

Exemple

Urmatorul exemplu demonstreaza cateva lucruri:

  1. Cum metoda static e implementata asupra unei clase.
  2. O clasa cu un membru static poate fi o sub-clasa.
  3. Cum o metoda static poate sau nu poate fi invocata.
class Triple {
  static triple(n) {
    if (n === undefined) {
      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

var tp = new Triple();

console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)

console.log(tp.triple());
// 'tp.triple is not a function'.

Specificatii

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Class definitions' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Class definitions' in that specification.
Draft  

Compatibilate browser

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support4911345 No369
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support ? Yes1345 ?9 Yes

1. From Chrome 42 to 48 strict mode is required. Non-strict mode support can be enabled using the flag "Enable Experimental JavaScript".

See also

Document Tags and Contributors

Contributors to this page: Mercur
Last updated by: Mercur,