static
Nyckelordet static definierar en statisk metod för en klass.
Syntax
static methodName() { ... }
Beskrivning
Anrop på statiska metoder är gjorda direkt på klassen och kan inte göras genom instanser av klassen. Statiska metoder är ofta använda för att göra verktygsfunktioner.
Att anropa statiska metoder
Från en annan statisk metod
För att anropa en statisk metod från en annan statisk metod av samma klass, kan du använda "this".
class StaticMethodCall {
static staticMethod() {
return 'En statisk metod har blivit anropad';
}
static anotherStaticMethod() {
return this.staticMethod() + ' från en annan statisk metod!';
}
}
StaticMethodCall.staticMethod();
// 'En statisk metod har blivit anropad'
StaticMethodCall.anotherStaticMethod();
// 'En statisk metod har blivit anropad från en annan statisk metod!'
Från en klasskonstruktor och andra metoder
Statiska metoder är inte tillgängliga genom att använda "this"
från icke statiska metoder. Du behöver anropa dem genom att antingen använda klassnamnet: ClassName.staticMethodName() eller genom att anropa metoden som en egendom av konstruktorn: this.constructor.staticMethodName().
class StaticMethodCall {
constructor() {
console.log(StaticMethod.staticMethod());
// 'En statisk metod har blivit anropad.'
console.log(this.constructor.staticMethod());
// 'En statisk metod har blivit anropad.'
}
static staticMethod() {
return 'En statisk metod har blivit anropad.';
}
}
Exempel
Det följande exemplet visar flera saker:
- Hur en statisk metod implementeras på en klass.
- Att en klass med en statisk medlem kan vara sub-klassad.
- Hur en statisk metod kan och inte kan bli anropad.
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 (Påverkas inte av förälderns instans.)
console.log(tp.triple());
// 'tp.triple is not a function'.
Specifikationer
Specifikation | Status | Kommentar |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Class definitions' in that specification. |
Standard | Första definition. |
ECMAScript (ECMA-262) The definition of 'Class definitions' in that specification. |
Living Standard |
Webbläsarkompatibilitet
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Funktion | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Grundlig support | 42.0 | 45 (45) | ? | ? | ? |
Funktion | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|
Grundlig support | No support | 45.0 (45) | ? | ? | ? | 42.0 |