Language: EN

metodos-y-variables-estaticos-en-clases

Static Methods and Variables in JavaScript

A static method or variable is one that belongs to the class, not to the instances of that class.

This means that static variables and methods are shared by all instances of the class.

Consequently, they cannot directly access instance properties, as they are not linked to any specific instance of the class.

Static Variables

In JavaScript, static variables are defined using the static keyword, which indicates that this property belongs to the class itself.

class Counter {
    static counter = 0;

    constructor() {
        Counter.counter++;
    }

    static getCounter() {
        return Counter.counter;
    }
}

const c1 = new Counter();
const c2 = new Counter();
const c3 = new Counter();

console.log(Counter.getCounter()); // Shows 3

In this example:

  • Counter.counter is a static variable that increments every time a new instance of the Counter class is created.
  • Counter.getCounter() is a static method that allows access to the value of the static variable counter, without needing to create an instance of the class.

Remember that static variables cannot be accessed through instances of the class. They are always accessed through the class itself.

Static Methods

Similarly, a static method is a method that belongs to the class rather than to an instance of the class. This means you can invoke the method directly on the class without needing to create an object.

Like variables, static methods are also defined using the static keyword.

class Mathematics {
    static add(a, b) {
        return a + b;
    }

    static subtract(a, b) {
        return a - b;
    }
}

console.log(Mathematics.add(5, 3));  // Shows 8
console.log(Mathematics.subtract(5, 3)); // Shows 2

Here

  • We have created a class called Mathematics with two static methods: add and subtract.
  • Both methods can be invoked without creating an instance of the class.