JavaScript static keyword

JavaScript static keyword 

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions.

Example:

class ClassWithStaticMethod {
 
static staticMethod() {
   
return 'static method has been called.';
 
}
}
console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."

static methods

In order to call a static method within another static method of the same class, you can use the this keyword.

class StaticMethodCall {
  static staticMethod() {
    return 'Static method has been called';
  }
  static anotherStaticMethod() {
    return this.staticMethod() + ' from another static method';
  }
}
StaticMethodCall.staticMethod();
// 'Static method has been called'

StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'

static fields or variable 

Public static fields are useful when you want a field to exist only once per class, not on every class instance you create. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

class ClassWithStaticField {
  static staticField = 'static field'
}

console.log(ClassWithStaticField.staticField)
// expected output: "static field"​





Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)