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 consoleconsole.log(`2`)}}// Calling the static function "printTwo" without creating an instance of the classStaticFunction.printTwo();
Static function definition
- We have the definition of a class named
StaticFunction
. This class has a single function namedprintTwo
on line 4 that has been marked asstatic
. This function simply prints the value2
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 isStaticFunction.printTwo()
.
Static properties
In a similar manner to ...