Static Methods

Frontend SELF EN
Level 40 , Lesson 1
Available

8.1 Declaring Static Methods

Static methods in JavaScript are methods that are defined on the class itself, not on its instances. They are called directly on the class, not on objects created by the class. Static methods are often used to create utility functions that are related to the class, but not to any specific object instance.

Static methods are declared using the static keyword before the method definition in the class body.

Example:

  • Methods add and multiply are declared as static using the static keyword
  • These methods are called directly on the MathHelper class, not on its instances
JavaScript
    
      class MathHelper {
        static add(a, b) {
          return a + b;
        }

        static multiply(a, b) {
          return a * b;
        }
      }

      console.log(MathHelper.add(5, 3)); // 8
      console.log(MathHelper.multiply(5, 3)); // 15
    
  

8.2 Using Static Methods

Static methods are useful in the following scenarios:

  1. Helper Functions: static methods can be used to create utility functions that perform operations associated with a class.
  2. Factory Methods: static methods can be used to create class instances with specific logic.
  3. Data Processing: static methods can be used to process data related to a class, but do not require creating class instances.

Example of helper functions:

  • Class StringUtil contains static methods capitalize and reverse that work with strings
  • These methods are called directly on the StringUtil class
JavaScript
    
      class StringUtil {
        static capitalize(str) {
          return str.charAt(0).toUpperCase() + str.slice(1);
        }

        static reverse(str) {
          return str.split('').reverse().join('');
        }
      }

      console.log(StringUtil.capitalize('hello')); // "Hello"
      console.log(StringUtil.reverse('hello')); // "olleh"
    
  

Example of a factory method:

The static method fromObject creates an instance of the Car class from a data object.

JavaScript
    
      class Car {
        constructor(brand, model) {
          this.brand = brand;
          this.model = model;
        }

        static fromObject(obj) {
          return new Car(obj.brand, obj.model);
        }
      }

      const carData = { brand: 'Toyota', model: 'Camry' };
      const car = Car.fromObject(carData);

      console.log(car.brand); // "Toyota"
      console.log(car.model); // "Camry"
    
  

8.3 Static Methods and Inheritance

In JavaScript, static methods are also inherited by derived classes. Derived classes can use static methods of the base class or override them.

Example of inheriting static methods:

  • Static method identify is defined in the Animal class and overridden in the Dog class
  • The identify method is called on both classes
JavaScript
    
      class Animal {
        static identify() {
          return 'This is an animal';
        }
      }

      class Dog extends Animal {
        static identify() {
          return 'This is a dog';
        }
      }

      console.log(Animal.identify()); // "This is an animal"
      console.log(Dog.identify()); // "This is a dog"
    
  

8.4 Accessing Static Methods Inside Other Methods

Static methods can be called within other class methods using the class name.

Example:

The static method calculateArea is called inside another static method describeCircle using the this keyword, which in this context refers to the Geometry class itself.

JavaScript
    
      class Geometry {
        static calculateArea(radius) {
          return Math.PI * radius * radius;
        }

        static describeCircle(radius) {
          const area = this.calculateArea(radius);
          return `A circle with radius ${radius} has an area of ${area.toFixed(2)}.`;
        }
      }

      console.log(Geometry.describeCircle(5)); // "A circle with radius 5 has an area of 78.54."
    
  

8.5 Static Methods and Class Instances

Static methods cannot be called on class instances. Attempting to call a static method on an instance will result in an error.

Example:

The static method add is called on the Calculator class, not on its instance calc.

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

      const calc = new Calculator();
      console.log(Calculator.add(3, 4)); // 7

      console.log(calc.add(3, 4)); // Error: calc.add is not a function
    
  
1
Task
Frontend SELF EN, level 40, lesson 1
Locked
Static Methods
Static Methods
1
Task
Frontend SELF EN, level 40, lesson 1
Locked
Factory Method User
Factory Method User
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION