add a public method to a class in javascript

To add a public method to a class in JavaScript, you can simply declare a function inside the class definition. Here's an example:

index.tsx
class MyClass {
  constructor() {
    // constructor code here
  }

  // public method
  myPublicMethod() {
    // method code here
  }

  // private method (using symbol)
  [Symbol("myPrivateMethod")]() {
    // method code here
  }
}
236 chars
16 lines

In the above code, myPublicMethod is a public method that can be called by anyone who has an instance of MyClass. The constructor function runs when you create a new instance of the class using the new keyword.

For private methods, you can use the Symbol function to create a unique key that can be used to access the method from within the class. This makes it accessible only to the class itself and not to any external code that may have an instance of the class.

gistlibby LogSnag