add a public static method to a class in javascript

To add a public static method to a class in JavaScript, you can directly assign a function to the class constructor function. Here's an example:

index.tsx
class MyClass {
  constructor(prop) {
    this.prop = prop;
  }
  
  static myStaticMethod() {
    console.log('This is a static method.');
  }
  
  myPublicMethod() {
    console.log(`This is a public method. Prop value is ${this.prop}.`);
  }
}

MyClass.myStaticMethod(); // This is a static method.

const obj = new MyClass('foo');
obj.myPublicMethod(); // This is a public method. Prop value is foo.
404 chars
19 lines

In the example above, myStaticMethod() is a public static method that belongs to the MyClass class. You can call it directly from the class constructor function, without creating an instance of the class.

On the other hand, myPublicMethod() is a public instance method that belongs to instances of the MyClass class. You can call it only by creating an instance of the class.

Note that the static keyword is used to define static methods in JavaScript. Similarly, you can add public instance methods by defining them in the class constructor function.

gistlibby LogSnag