...

/

Static Functions and Namespaces

Static Functions and Namespaces

Learn how to use static functions and properties in classes to have a single instance of a function or property throughout the code base.

Static functions

A class can mark a function with the static keyword, meaning that there will only be a single instance of this function available throughout the code base.

When using a static function, we do not need to create an instance of the class in order to invoke this function, as follows:

// Declaring a class named "StaticFunction"
class StaticFunction {
// Declaring a static function named "printTwo"
static printTwo() {
// Logging the value "2" to the console
console.log(`2`)
}
}
// Calling the static function "printTwo" without creating an instance of the class
StaticFunction.printTwo();
Static function definition
  • We have the definition of a class named StaticFunction. This class has a single function named printTwo on line 4 that has been marked as static. This function simply prints the value 2 to the console.

Note: We do not need to create an instance of this class using the new keyword. We simply call this function by its fully qualified name, that is, <className>.<functionName>, which in this case is StaticFunction.printTwo().

Static properties

In a similar manner to ...