I am using the exact code he uses in ES6 Classes( Private Members Using WeakMaps.) From the beginning to 2:34 in the video. The draw method is in the prototype, but I can not get the radius value. When I type c.draw() in the console it says undefined
Can you include your code? Here’s how to format it for a post.
`const _radius = new WeakMap();
class Circle {
constructor(radius) {
_radius.set(this, radius);
}
draw() {
console.log(_radius.get(this));
}
}
const c = new Circle(1);
The console is showing you the return value of the draw
method, but your draw
method has no return value. In other words, the return value is undefined
. If you return a value, then you will see that value in the console.
draw() {
const value = _radius.get(this);
return value;
}
I tried your code and I get the same result. I think the behavior of WeakMaps has changed since this video. I didn’t have any issues with the preceding Symbols exercise.
`const _radius = new WeakMap();
class Circle {
constructor(radius) {
_radius.set(this, radius);
}
draw() {
const value = _radius.get(this);
return value;
}
}
const c = new Circle(1);
If you run this code you don’t see The radius is: 1
?
const _radius = new WeakMap();
class Circle {
constructor(radius) {
_radius.set(this, radius);
}
draw() {
const value = _radius.get(this);
return value;
}
}
const c = new Circle(1);
console.log('The radius is: ', c.draw());
Thanks, it did work. I don’t understand why the console.log in the draw method worked for Mosh in his video, but not for me and I copied his code verbatim?
Are you doing this in the Chrome console? You may need to select “user messages” on the left.
Thanks, I wasn’t aware of that option