Javascript private fields are coming

Warren Parad - May 15 '19 - - Dev Community

Turns out that node stage 3 right now we will have private class properties. And it is exactly as you thought it would be:

class Point {
    private int x = 0;
    public int y = 0;
}

Just kidding it is actually

class Point {
  #x;
  y;

  constructor(x, y) {
    this.#x = x;
    this.y = y;
  }

  equals(point) {
    return this.#x === point.#x && this.y === point.y;
  }
}

Queue a bunch of WTF moments.

So I started to search around for a bit for an explanation, because surely there must be a good reason. And there are lots of people trying to explain and they haven't got that far. And I came across where one guy would try to explain it:

Jamie.build

Reason:
(1) Because of #encapsulation (see the "Encapsulation" section above), we need to allow public and private fields with the same name at the same time. So accessing a private field can't just be a normal lookup.

Wait why is that? Why do we need to allow private and public fields with the same name.

(2) Private fields won't be able to support the second syntax (because it needs to be static) and that could lead to confusion

That statement leads to confusion, what needs to be static, are we saying that private properties need to be static. No, they clearly aren't static, because each instance has a different property.

(3) We need to support this.#x === other.#x && this.#y === other.#y;

No you don't and actually and wait a second, how do you even know that other has a #x in the first place

class Point {
  #x;
  equals(otherPoint) {
    return this.#x === otherPoint.#x;
  }
}

Are you telling me that if otherPoint is a Point this function works, but if otherPoint isn't a point, then this just magically crashes. This means we are going to have runtime type checks for javascript properties in methods.

WAT!

So the reason we have # for private properties is to support functionality that no one needs or no one can understand like "well it would be confusing otherwise"

Here is the official reasoning

I wish someone could explain that in layman's terms, because it sounds a lot like "Well Java allows that so we should too." Actually I don't know how many languages allow this, but I would inherently expect that this to be expressly forbidden. It isn't a public property, why should even other instances of the class have access to it.

Actually the rest of the "arguments on the github tc39 proposal don't even come close to justifying the reason for this. So it seems we will be stuck with this nonsense for no good reason.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player