Reputation: 11
I am trying to figure out what is different between defining local/private properties and methods inside a class compared to WeakMap constructor?
is the purpose of hiding them from outside are the same or is there other thing to use them?
Upvotes: 0
Views: 189
Reputation: 371019
Given your current implementation:
let x
isn't very useful, because it can only be referenced in the constructor. It can't be used in any of the prototype methods. The WeakMap, on the other hand, can be referenced anywhere. That's a pretty big difference.radius
value that you wanted to be private.If you wanted the WeakMap to be properly private, via closures, you could use an IIFE to define the class, eg:
const myClass = (() => {
const weakMap = new WeakMap();
return class Circle {
// etc
})();
That way, the top level only has a reference to the myClass
, and not to the weakMap
.
I would use your let x
in the constructor whenever a variable is only needed in the constructor - not necessarily for the sake of hiding data, but just because it has no use outside of the constructor. See Why is it good programming practice to limit scope?
Note that there is currently a proposal for class fields which will probably eventually be implemented, which includes syntax for private fields, eg:
class Circle {
constructor(radius) {
this.#x = radius;
// ...
This will allow #x
to be accessed from anywhere within Circle
, but nowhere else. It's functionally equivalent to the WeakMap
implementation.
Upvotes: 1