在JavaScript公共方法中获取私有方法的返回值
Fixing Undefined Output When Calling Private Method via WeakMap in JavaScript Circle Class
Let's walk through the issues in your code and get that area calculation working correctly:
What's Causing the undefined Output?
- You never stored the private method in your WeakMap: Your
_areaCalculateWeakMap is empty for each Circle instance—you only set the_radiusvalue in the constructor, never the method itself. - Incorrect method definition syntax: Using
[_areaCalculate]()as a class method doesn't bind that function to your WeakMap._areaCalculateis a WeakMap instance, not a Symbol or valid property key, so this creates a weirdly named method that's never linked to your WeakMap. - Accessing the radius incorrectly:
this.radiusdoesn't exist—your radius is stored privately in the_radiusWeakMap, so you need to retrieve it with_radius.get(this).
Corrected Code Option 1 (Inline Method in Constructor)
const _radius = new WeakMap(); const _areaCalculate = new WeakMap(); class Circle { constructor(r) { _radius.set(this, r); // Store the private calculation method in the WeakMap for this instance _areaCalculate.set(this, () => { // Retrieve the private radius from its WeakMap const radius = _radius.get(this); return (Math.PI * Math.pow(radius, 2)).toFixed(2); }); } areaPrint() { // Get the method from the WeakMap and execute it const calculateArea = _areaCalculate.get(this); console.log("The area of Circle is: " + calculateArea()); } } let c = new Circle(4); c.areaPrint(); // Output: The area of Circle is: 50.27
Corrected Code Option 2 (Reusable External Function)
If you want to reuse the calculation logic across instances, define the function separately and bind it to the correct this context:
const _radius = new WeakMap(); const _areaCalculate = new WeakMap(); // Private function defined outside the class function calculateCircleArea() { const radius = _radius.get(this); return (Math.PI * Math.pow(radius, 2)).toFixed(2); } class Circle { constructor(r) { _radius.set(this, r); // Bind the function to this instance and store it in the WeakMap _areaCalculate.set(this, calculateCircleArea.bind(this)); } areaPrint() { // Retrieve and invoke the private method console.log("The area of Circle is: " + _areaCalculate.get(this)()); } } let c = new Circle(4); c.areaPrint(); // Output: The area of Circle is: 50.27
Key Fixes Explained
- Storing the method in WeakMap: We explicitly add the calculation function to
_areaCalculatefor each instance in the constructor, so_areaCalculate.get(this)returns the actual method instead ofundefined. - Invoking the method: Instead of just getting the method reference, we add
()to execute it and get the calculated area value. - Accessing private radius: We use
_radius.get(this)to fetch the stored private radius value, sincethis.radiusisn't a defined property on the instance.
内容的提问来源于stack exchange,提问作者mrhrifat
相关产品推荐
相关产品推荐

