Understanding what Static does in Javascript
Shanoy Sinclair
Posted on September 12, 2020
I am sure you have probably watched a tutorial of Javascript where the instructor have used the static method on a class and not fully explain what static even does. Here is a simple explanation of what the functionalities are as stated by the Mozilla Developer Network.
The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects eg.
class Greet {
static sayHi() {
console.log("hello");
}
}
Greet.sayHi(); // return 'hello'
If we were to create an instance and call the method sayHi on that instance we would get a TypeError of not a function eg.
const greeting = new Greet();
greeting.sayHi(); // return TypeError: greeting.sayHi is not a function
For more information on Static methods: click here
Posted on September 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 28, 2024
May 26, 2024