8.1 Declaring Static Methods
Static methods in JavaScript are methods that are defined on the class itself, not on its instances. They are called directly on the class, not on objects created by the class. Static methods are often used to create utility functions that are related to the class, but not to any specific object instance.
Static methods are declared using the static
keyword before the method definition in the class body.
Example:
- Methods
add
andmultiply
are declared as static using thestatic
keyword - These methods are called directly on the
MathHelper
class, not on its instances
class MathHelper {
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
}
console.log(MathHelper.add(5, 3)); // 8
console.log(MathHelper.multiply(5, 3)); // 15
8.2 Using Static Methods
Static methods are useful in the following scenarios:
- Helper Functions: static methods can be used to create utility functions that perform operations associated with a class.
- Factory Methods: static methods can be used to create class instances with specific logic.
- Data Processing: static methods can be used to process data related to a class, but do not require creating class instances.
Example of helper functions:
- Class
StringUtil
contains static methodscapitalize
andreverse
that work with strings - These methods are called directly on the
StringUtil
class
class StringUtil {
static capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
static reverse(str) {
return str.split('').reverse().join('');
}
}
console.log(StringUtil.capitalize('hello')); // "Hello"
console.log(StringUtil.reverse('hello')); // "olleh"
Example of a factory method:
The static method fromObject
creates an instance of the Car
class from a data object.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
static fromObject(obj) {
return new Car(obj.brand, obj.model);
}
}
const carData = { brand: 'Toyota', model: 'Camry' };
const car = Car.fromObject(carData);
console.log(car.brand); // "Toyota"
console.log(car.model); // "Camry"
8.3 Static Methods and Inheritance
In JavaScript, static methods are also inherited by derived classes. Derived classes can use static methods of the base class or override them.
Example of inheriting static methods:
- Static method
identify
is defined in theAnimal
class and overridden in theDog
class - The
identify
method is called on both classes
class Animal {
static identify() {
return 'This is an animal';
}
}
class Dog extends Animal {
static identify() {
return 'This is a dog';
}
}
console.log(Animal.identify()); // "This is an animal"
console.log(Dog.identify()); // "This is a dog"
8.4 Accessing Static Methods Inside Other Methods
Static methods can be called within other class methods using the class name.
Example:
The static method calculateArea
is called inside another static method describeCircle
using the this
keyword, which in this context refers to the Geometry
class itself.
class Geometry {
static calculateArea(radius) {
return Math.PI * radius * radius;
}
static describeCircle(radius) {
const area = this.calculateArea(radius);
return `A circle with radius ${radius} has an area of ${area.toFixed(2)}.`;
}
}
console.log(Geometry.describeCircle(5)); // "A circle with radius 5 has an area of 78.54."
8.5 Static Methods and Class Instances
Static methods cannot be called on class instances. Attempting to call a static method on an instance will result in an error.
Example:
The static method add
is called on the Calculator
class, not on its instance calc
.
class Calculator {
static add(a, b) {
return a + b;
}
}
const calc = new Calculator();
console.log(Calculator.add(3, 4)); // 7
console.log(calc.add(3, 4)); // Error: calc.add is not a function
GO TO FULL VERSION