JavaScript: How to use arguments of a class constructor in the methods without defining them as a property

Viewed 23

I want to use arguments of a class constructor in the methods and I don't want to put the methods inside the constructor for this.
I also don't want to set constructor arguments as class property.
So I need something like this:

class ElemArith {
  constructor(num1) { }
  add(num2)  {return num1 + num2;}
  sub(num2)  {return num1 - num2;}
  mult(num2) {return num1 * num2;}
  div(num2)  {return num1 / num2;}
}

I know I can use the new syntax of defining private property in the class like the following code but I want to know if there is a better way for my purpose.

class ElemArith {
  #num1;
  constructor(num1) {
    this.#num1 = num1;
  }
  add(num2) {return this.#num1 + num2}
  sub(num2) {return this.#num1 - num2}
  mult(num2) {return this.#num1 * num2}
  div(num2) {return this.#num1 / num2}
}

const newArith = new ElemArith(3);
console.log(newArith.add(6));
console.log(newArith.sub(1));
console.log(newArith.num1);
// console.log(newArith.#num1); // causing SyntaxError

0 Answers
Related