Lightweight Protected Fields

This is a well thought-out proposal. We have actually discussed protected fields in the past, but failed to come up with a way to actually implement them in JavaScript (see here, and I just found this thread as well while looking for the other one).

One of the things we got stuck on in the previous thread, was how to actually implement protected. I think you're getting really close to something. Bouncing off of your ideas, and a few of my own thoughts, I think it would be possible to create protected logic.

Take this code example:

class BaseClass {
  #x
  constructor(x) {
    this.#x = x
  }

  protected #getSecretValue() {
    return this.#x
  }
}

class SubClass extends BaseClass {
  logSecretValue() {
    console.log(super.#getSecretValue())
  }
}

This can be implemented, behind the scenes, as follows. [[homeObject]] represents the homeObject hidden field, and [[protectedFields]] is a new hidden field that contains a mapping of hidden field names to values.

class BaseClass {
  #x
  constructor(x) {
    this.#x = x
  }

  protected #getSecretValue() {
    return this.#x
  }

  [[hiddenFields]]: new Map([
    ['getSecretValue', this.#getSecretValue]
  ])
}

class SubClass extends BaseClass {
  logSecretValue() {
    console.log(super[[hiddenFields]].get('getSecretValue').call(this))
  }
}

There's a couple of restrictions with how this machinery works. First, it's only designed to work with methods. Secondly, when you access a super-class protected field, you must also call it (thus, making it impossible to, for example, .call() the protected field with another value). I bet there are ways to lift these restrictions, but I think this alone would be a good starting point that many people would be happy with.

As a side note - I like the syntax of using super.#whatever() to access protected properties. I think it looks clean to have protected access look different from private access.


With all of this said, I'm actually not the biggest fan of the protected access modifiers. It's something I've been doing a lot of researching and learning about recently, and I've come to believe that there's always a better way to structure one's code, than to use a protected-enabled class, which means, I also believe that adding protected to the language would encourage people to write worse code. If interested, there's an ongoing discussion about inheritance in general, that doesn't (yet) talk about protected directly, but does discuss items closely related, and the overall value of protected fields would be an on-topic discussion point over there. Either way, I just wanted to quickly express this opinion, but I don't want to pollute this thread with a discussion around it.