add a method to a class in javascript

To add a method to a class in JavaScript, you can use the prototype property. Here's an example:

index.tsx
class MyClass {
  constructor(name) {
    this.name = name;
  }

  // method to add
  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

// create an instance of MyClass
const myInstance = new MyClass("John");

// call the sayHello method
myInstance.sayHello(); // Output: Hello, John!
296 chars
17 lines

In the example above, we added the sayHello method to the MyClass class using the prototype property. This method can then be called on any instance of the MyClass class.

gistlibby LogSnag