JavaScript Class Static
JavaScript Static Methods
JavaScript static methods are methods that belong to the class itself, rather than to instances of the class. They can be called directly on the class, without the need for an instance to be created first.
Here are some key points about static methods in JavaScript:
- To define a static method in a class, you use the
"static"
keyword before the method name.
As an example:
class MyClass {
static myStaticMethod() {
console.log("This is a static method");
}
}
- Static methods can be called directly on the class, using the class name and the dot notation.
As an example:
MyClass.myStaticMethod(); // Output: "This is a static method"
- Static methods cannot be called on instances of the class.
As an example:
const myInstance = new MyClass();
myInstance.myStaticMethod(); // This will result in an error
- Static methods can access only static properties and methods of the class, and cannot access instance properties or methods. This is because they do not have access to the
"this"
keyword.
As an example:
class MyClass {
static myStaticMethod() {
console.log(MyClass.myStaticProperty);
}
static myStaticProperty = "This is a static property";
myInstanceMethod() {
console.log("This is an instance method");
}
}
MyClass.myStaticMethod(); // Output: "This is a static property"
const myInstance = new MyClass();
myInstance.myInstanceMethod(); // Output: "This is an instance method"
myInstance.myStaticMethod(); // This will result in an error
- Static methods are useful for utility functions that are related to the class but do not require access to instance-specific data. They can also be used to implement factory methods that create instances of the class.