Basics

In JavaScript, static methods are methods that are associated with a class itself, rather than with instances of the class. They can be called without creating an instance of the class, using the name of the class followed by the method name, like this:

class MathUtils {
  static sum(a, b) {
    return a + b;
  }
}

console.log(MathUtils.sum(1, 2)); // 3

Static methods are often used for utility functions that do not need to access or modify the instance state of a class.

Method chaining is a technique for calling multiple methods on the same object, one after the other, in a single statement. Each method returns the object itself, allowing you to chain the method calls together. Here is an example of method chaining in JavaScript:

class StringBuilder {
  constructor(string) {
    this._string = string;
  }
  
  append(string) {
    this._string += string;
    return this;
  }
  
  prepend(string) {
    this._string = string + this._string;
    return this;
  }
  
  toString() {
    return this._string;
  }
}

const builder = new StringBuilder("Hello");
const result = builder.append(", World!").prepend("Hi, ").toString();
console.log(result); // "Hi, Hello, World!"

In this example, we have a StringBuilder class with three methods: append, prepend, and toString. The append and prepend methods return the StringBuilder object itself, allowing the methods to be chained together. The toString method returns the final string value.

Static methods and method chaining are not directly related, but they can be used together in a class if needed. For example, you could define a static method that creates and returns a new instance of a class, and then chain method calls onto that instance:

class MathUtils {
  static sum(a, b) {
    return a + b;
  }
  
  static createSummation(a, b) {
    return new Summation(a, b);
  }
}

class Summation {
  constructor(a, b) {
    this._a = a;
    this._b = b;
  }
  
  add(c) {
    this._a += c;
    return this;
  }
  
  toString() {
    return `${this._a} + ${this._b} = ${this._a + this._b}`;
  }
}

const result = MathUtils.createSummation(1, 2).add(3).toString();
console.log(result); // "6 + 2 = 8"

In this example, we have a MathUtils class with a static createSummation method that creates and returns a new Summation object. We can then chain method calls onto the Summation object using method chaining.

Last updated