Search⌘ K

Static Methods

Explore how static methods in JavaScript classes function as class-level methods accessible only on the class itself. Learn to define and use static methods using the ES6 static keyword, understand their difference from prototype methods, and see practical examples such as comparing student marks without relying on specific object instances.

What are Static Methods?

Methods that we define inside the class get assigned to the prototype object of the class and belong to all the objects instances that get created from that class.

Let’s consider the example of the class Student:

Javascript (babel-node)
class Student {
constructor(name,age,sex,marks) {
this.name = name
this.age = age
this.sex = sex
this.marks = marks
}
//method defined in class gets assigned to the prototype of the class Students
displayName(){
console.log("Name is:", this.name)
}
}
var student1 = new Student('Kate',15,'F',20)
student1.displayName()
console.log("Age:",student1.age)
console.log("Sex:",student1.sex)
console.log("Marks:",student1.marks)

The class Student has the method displayName defined. Any object instance created will inherit this method from Student.prototype just as student1 inherits it.

Now, let’s suppose we have multiple ...