You are currently viewing Best Way to Creating Class Private Method in JavaScript

Best Way to Creating Class Private Method in JavaScript

JavaScript Class Private Method

In this article, we will see what is a javascript class private method and how to create it.

What is the private method?

If the methods that can only be accessed within the class in which they are defined is called private method in javascript. These methods are marked as private using the hash ‘#’ symbol before the method name. This method controls access to them and prevents other parts of the code from depending on them. It can be useful for encapsulating implementation without exposure to other parts of the code.

Why should we create a private method?

  • Private methods can encapsulate logic within a class and prevent external code from modifying or accessing the class’s internal state.
  • It can help organize the code of a class by separating public and private methods, making the code easier to read and maintain.
  • Private methods can be used to implement security features, such as password hashing, that should not be accessible outside the class.

A step-by-step guide to creating a private method

  1. Create the class ‘Example’ using the ‘class‘ keyword.
  2. Declare the private method inside the ‘Example’ class, using the ‘#‘ hash symbol before the method name. For example, #private(). It will make the normal method into a private method in the class.
  3. Then create a normal method inside the class without using the ‘#’ hash symbol.
  4. To access the private method from within the class, use the ‘this’ keyword followed by the method name. For example, this.#private()
  5. To access the private method from outside the class, we will need to define a public getter or a setter method.
class Example {
  #private() {
    console.log("This is a private method");
  }

  public() {
    console.log("This is a public method");
    this.#private();
  }

  getPrivate() {
    this.#private();
  }
}

const example = new Example();
example.public();  // Output: "This is a public method" "This is a private method"
example.getPrivate(); // Output: "This is a private method"

In this example code, we have created the ‘private()‘ method inside the class using ‘#’ symbol. The ‘public()’ is a public method that can be called from outside the class and which calls the private method using ‘this.#private()‘. The ‘getPrivate‘ is a public method that can also be called from outside the class, but only calls the private method without doing anything else.

Leave a Reply