Adnan Masoud
Adnan Masoud

Reputation: 11

Is there any difference between WeakMap and private member of a class in JavaScript ES6?

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?

enter image description here

Upvotes: 0

Views: 189

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

Given your current implementation:

  • Your 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.
  • Your WeakMap can be referenced anywhere. This means that it's not actually providing any privacy; anything with a reference to an instance and the WeakMap may access the 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

Related Questions