Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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()

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!