Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Class Static in JavaScript

Class Static in JavaScript

?? Static Methods and Properties in JavaScript Classes


What are Static Members?

  • Static methods/properties belong to the class itself, not to instances (objects created from the class).

  • You call them directly on the class, not on an object.

  • Useful for utility functions or constants related to the class.


Syntax

class MyClass {  static staticMethod() {    console.log("This is a static method.");  }  static staticProperty = "Static property value";  instanceMethod() {    console.log("This is an instance method.");  }}// Calling static methodMyClass.staticMethod();  // Output: This is a static method.// Accessing static propertyconsole.log(MyClass.staticProperty);  // Output: Static property value// Trying to call static method on instance (will fail)const obj = new MyClass();obj.staticMethod();  // Error: obj.staticMethod is not a function

Example: Static vs Instance

class Circle {  constructor(radius) {    this.radius = radius;  }  // Instance method  area() {    return Math.PI * this.radius ** 2;  }  // Static method  static description() {    return "Circles are round shapes.";  }}const c = new Circle(5);console.log(c.area());              // Output: 78.53981633974483console.log(Circle.description()); // Output: Circles are round shapes.

Use Cases for Static Methods

  • Utility/helper functions related to the class but not tied to an instance

  • Factory methods to create instances

  • Constants related to the class


Static Properties Support

  • Supported in modern JavaScript (ES2022+)

  • For older environments, static properties can be assigned outside the class:

class Example {}Example.staticValue = 123;console.log(Example.staticValue);  // 123

Would you like examples of static factory methods, or using static properties for constants?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql