Search code examples
javascriptinstance-variableses6-classprivate-members

Get Private Method Value at Public Method in JavaScript


I have Created a Class Circle. Here

  1. _radius is a private parameter
  2. _areaCalculate is a private method

After Calculate the value from private method _areaCalculate. I need this value to public method areaPrint. But it show me undefined.

const _radius = new WeakMap()
const _areaCalculate = new WeakMap()

class Circle {
    constructor(r) {
        _radius.set(this, r)
    }
    [_areaCalculate]() {
        return (Math.PI * Math.pow(this.radius, 2)).toFixed(2)
    }

    areaPrint() {
        console.log("The area of Circle is: " + _areaCalculate.get(this))
    }
}
let c = new Circle(4)
c.areaPrint()


Solution

  • If one sticks with the OP's approach of utilizing a weak map for accessing a Circle instance' "private member" through a prototypal method, then one just needs to simplify the code to a single reference map and a function which calculates a circle instance' area on the fly ...

    function getComputedArea(circle) {
      return (Math.PI * Math.pow(rMap.get(circle), 2)).toFixed(2);  
    }
    const rMap = new WeakMap();
    
    class Circle {
      constructor(radius) {
        rMap.set(this, radius);
      }
      areaPrint() {
        console.log(
          `A radius ${ rMap.get(this) } circle area is ${ getComputedArea(this) }`
        );
      }
    }
    let a = new Circle(4);
    let b = new Circle(9);
    
    a.areaPrint();
    b.areaPrint();

    ... or one follows VLAZ's advice and starts utilizing the private field declaration syntax for private instance fields.

    Edit

    From the further beneath comment-based discussion with Bergi ...

    "Private methods, unlike private fields, are allocated on the prototype not on the instance, just the like their respective public counterparts" . – Bergi

    ... the implementation for getComputedArea changed from a local helper function to a private instance method.

    class Circle {
    
      #getComputedArea(radius) {
        return (Math.PI * Math.pow(this.#radius, 2)).toFixed(2);
      }
      #radius;
    
      constructor(radius) {
        this.#radius = radius;
      }
      areaPrint() {
        console.log(
          `A radius ${ this.#radius } circle area is ${ this.#getComputedArea() }`
        );
      }
    }
    let a = new Circle(4);
    let b = new Circle(9);
    
    a.areaPrint();
    b.areaPrint();