Skip to content

Static Methods

Short explanation

The static keyword is used in classes to declare static methods. Static methods are functions in a class that belongs to the class object and are not available to any instance of that class.

Sample code

class Repo {
  static getName() {
    return "Repo name is modern-js-cheatsheet"
  }
}

// Note that we did not have to create an instance of the Repo class
console.log(Repo.getName()) // Repo name is modern-js-cheatsheet

let r = new Repo();
console.log(r.getName()) // Uncaught TypeError: r.getName is not a function

Detailed explanation

Static methods can be called within another static method by using the this keyword, this doesn't work for non-static methods though. Non-static methods cannot directly access static methods using the this keyword.

Calling other static methods from a static method.

To call a static method from another static method, the this keyword can be used like so;

class Repo {
  static getName() {
    return "Repo name is modern-js-cheatsheet"
  }

  static modifyName() {
    return this.getName() + '-added-this'
  }
}

console.log(Repo.modifyName()) // Repo name is modern-js-cheatsheet-added-this

Calling static methods from non-static methods.

Non-static methods can call static methods in 2 ways; 1. #### Using the class name.

To get access to a static method from a non-static method we use the class name and call the static method like a property. e.g ClassName.StaticMethodName

class Repo {
  static getName() {
    return "Repo name is modern-js-cheatsheet"
  }

  useName() {
    return Repo.getName() + ' and it contains some really important stuff'
  }
}

// we need to instantiate the class to use non-static methods
let r = new Repo()
console.log(r.useName()) // Repo name is modern-js-cheatsheet and it contains some really important stuff
  1. Using the constructor

Static methods can be called as properties on the constructor object.

class Repo {
  static getName() {
    return "Repo name is modern-js-cheatsheet"
  }

  useName() {
    // Calls the static method as a property of the constructor
    return this.constructor.getName() + ' and it contains some really important stuff'
  }
}

// we need to instantiate the class to use non-static methods
let r = new Repo()
console.log(r.useName()) // Repo name is modern-js-cheatsheet and it contains some really important stuff

External resources