Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define private methods in a JS Class

I'm trying to define a private method for a class to test that such a method can't be called from outside the class. However, I'm coming across an error even when I'm using the syntax as indicated in the Specification. I also checked MDN.

Here's the code for my class:

class CoffeeMachine {
  #waterLimit = 200;

  #checkWater(value) {
    if (value < 0) throw new Error("Negative water");
    if (value > this.#waterLimit) throw new Error("Too much water");
  }
}

const coffeeMachine = new CoffeeMachine;

coffeeMachine.#checkWater();

Upon calling coffeeMachine.#checkWater();, I'm supposed to get an error indicating that such a method can't be called from outside the class, but instead, I'm getting Uncaught SyntaxError: Unexpected token '('.

What could be the reason for this?

like image 748
Mauric.io Avatar asked Nov 20 '19 20:11

Mauric.io


People also ask

How do you create a private method in JavaScript?

To make a public method private, you prefix its name with a hash # . JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }

How do I make my class methods private?

The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.

How do you declare private variables in classes in JavaScript?

Private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with # . The # is a part of the name itself. Private fields are accessible on the class constructor from inside the class declaration itself.

How do you define a private method?

A private method is an access modifier used in a class that can only be called from inside the class where it is defined. It means that you cannot access or call the methods defined under private class from outside. Consider a real-life example as a car engine.


3 Answers

In Javascript, you need to declare private variables private variables are declared by putting "#" in front of them (as seen in my example). Be sure to declare them outside of the constructor function

    class foo {
        #bar;// declare private variable called bar

        constructor() {
            this.#bar = "foobar";//define private variable called"bar"
        }
    }
like image 66
Yureadingthis Avatar answered Oct 08 '22 00:10

Yureadingthis


I think private methods (#myMethod()) and fields (#myField) are experimental features [source: developer.mozilar.org ] and at stage 3 for consideration but I managed to make it work by defining it to be as field and assigning it a function as follows;

#checkWater = (value) => {
  if (value < 0) throw new Error("Negative water");
  if (value > this.#waterLimit) throw new Error("Too much water");
}

OR

#checkWater = function(value) {
  if (value < 0) throw new Error("Negative water");
  if (value > this.#waterLimit) throw new Error("Too much water");
}

Now call it on the instance object as

coffeeMachine.#checkWater();

Let me hasten to add that, this code works in Google Chrome (1st image) but when tested in FireFox (2nd image), it did not run.

enter image description here

enter image description here

You should be okay with it hopefully!

like image 44
bafrimpong Avatar answered Oct 07 '22 23:10

bafrimpong


You example works in my Node.js 14.13.0 environment! Of course you need a public method to consume a private one. So here my working example:

   class CoffeeMachine {
     #waterLimit = 200

     #checkWater(value) {
       if (value < 0) throw new Error("Negative water")
       if (value > this.#waterLimit) throw new Error("Too much water")
       console.log(`@VALUE ${value}`)
     }

     checkWater(value) {
       this.#checkWater(value)
     }
   }

   const coffeeMachine = new CoffeeMachine()
   coffeeMachine.checkWater(20)
like image 30
cicciosgamino Avatar answered Oct 07 '22 23:10

cicciosgamino