add a private method to a class in javascript

To add a private method to a class in JavaScript, you can define the method within the constructor or any other class method using the const or let declaration with a function expression or arrow function.

Here is an example syntax:

index.tsx
class MyClass {
  constructor() {
    const privateMethod = () => {
      //code for private method here
    }
  }
}
117 chars
8 lines

In this example, privateMethod is defined inside the constructor using an arrow function. This means that privateMethod is only accessible within the MyClass constructor and not from outside the class.

You can also define a private method within another class method:

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

  publicMethod() {
    const privateMethod = () => {
      //code for private method here
    }
    // calling privateMethod
    privateMethod();
  }
}
208 chars
14 lines

In this example, privateMethod is defined inside the publicMethod() and can also only be accessed within that method.

gistlibby LogSnag