JavaScript Static Methods
Static methods are methods that are decorated with the static
keyword, also known as class methods. They belong to the class but not to the object. Static methods can be invoked before instantiating the object using ClassName.methodName
.
Static methods cannot be called on objects, only on the class itself.
Example
class tutorialpro {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
let noob = new tutorialpro("tutorialpro.org");
// Static method 'hello()' can be called within the class
document.getElementById("demo").innerHTML = tutorialpro.hello();
// Static methods cannot be called on instantiated objects
// document.getElementById("demo").innerHTML = noob.hello();
// The above code will throw an error
Calling a static method on an instance object will result in an error:
If you want to use a static method within the object noob
, you can pass it as a parameter:
Example
class tutorialpro {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
let noob = new tutorialpro("tutorialpro.org");
document.getElementById("demo").innerHTML = tutorialpro.hello(noob);