Skip to content
This repository was archived by the owner on Jan 25, 2022. It is now read-only.
This repository was archived by the owner on Jan 25, 2022. It is now read-only.

This proposal does not address the actually existing needs for private fields #22

@zocky

Description

@zocky

I'm aware that much of this has been covered in the FAQ, but I still want to chime in:

The only good reason for this (IMO ugly, but that's a matter of taste) syntax seems to be the complications with what is accessible from "this" and the desire to give other objects in the same class access to the private properties.

But this idea that other objects of the same class should have access to the private fields of an object is what is very non-Javascript.

JavaScript objects don't really have classes, they have inheritable prototypes. All it takes for another object to become "of the same class" is to set its __proto__ property to some class's prototype. Which could be considered "dirty", but is also very common across libraries. All it takes to add a method to a "class" is to add a function member to the class's prototype. So protection by classes is ineffective and meaningless.

What Javascript programmers traditionally do is restrict access to data by scope, not by class. This is why there is a very common pattern that goes like this:

function myFactory () {
  var foo = "bar";
  var myNewObject = {
     doSomethingWithFoo() {
        // foo is accessible here, but nowhere outside the myFactory function
        doSomething(foo);
     }
  }
  return myNewObject;
}

This is what Javascript programmers call "private" variables. It is not the same thing as in Java or other programming languages. But it is very useful for our use cases , because it prevents programmatic access to these "private" variables and thus protects the information from other, potentially malicious scripts outside our control, in the same window (if we're talking about browsers).

The pattern is very tedious to write, and cannot be easily (or at all?) converted to using classes. A proposal that would solve this problem, and not the problem of making Javascript classes more like
classes in other languages, would be preferable.

What we really need is this:

class myClass() {
  private foo = "bar";
  doSomethingWithFoo() {
     // foo is accessible here, but not accessible to methods of this or any other object
     // defined outside the class definition 
     doSomething(foo);
   }
} 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions