JavaScript Static Properties and Methods
In JavaScript, static
properties and methods belong to the class itself, not the instances of the class. This is useful when you need shared functionality that doesn’t depend on a specific object.
š¹ Defining Static Methods (static
keyword)
Static methods are defined using the static
keyword and can only be called on the class itself, not on instances.
✅ Example: Static Method
✔ add()
is a static method and must be called using the class name MathUtils.add()
.
✔ Calling it on an instance (mathObj.add()
) results in an error.
š¹ Defining Static Properties
Static properties are also defined with static
, and they belong to the class rather than instances.
✅ Example: Static Property
✔ brand
is a static property, accessible only via Car.brand
.
✔ Instances cannot access static properties.
š¹ Using this
in Static Methods
In static methods, this
refers to the class itself, not an instance.
✅ Example: this
in Static Methods
✔ this.count
refers to Counter.count
, not an instance property.
š¹ Static Methods in Class Inheritance
Static methods are inherited by child classes.
✅ Example: Static Method Inheritance
✔ Child
inherits the hello()
method from Parent
.
✅ Example: Overriding Static Methods
✔ The Child
class overrides the static method from Parent
.
š¹ When to Use Static Methods & Properties?
✔ Utility functions that don’t rely on instance properties (e.g., Math.sqrt()
).
✔ Counters, configurations, or shared state (static count
).
✔ Factory methods to create new instances in a controlled way.
šÆ Summary
✔ static
methods & properties belong to the class, not instances.
✔ Call them using the class name (ClassName.method()
).
✔ Static methods can be inherited and overridden.
✔ this
inside static methods refers to the class itself.
š Got any questions? Let me know! š