Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created July 11, 2019 02:53
Show Gist options
  • Save okovalov/9d96bdd94d6f5d7994ac4efeb7093bf0 to your computer and use it in GitHub Desktop.
Save okovalov/9d96bdd94d6f5d7994ac4efeb7093bf0 to your computer and use it in GitHub Desktop.

JavaScript Private Class Fields

taken from https://flaviocopes.com/javascript-private-class-fields/

Introduction and code samples on using private class fields in JavaScript.

Before the introduction of private class fields, we could not really enforce private properties on a class. We used conventions instead, maybe using _ as an hint that the field is private, like this:

class Counter {
  _count = 0

  increment() {
    this._count++
  }
}

But we could access the count using

const counter = new Counter()
counter._count

We can now use private class fields that enforce private fields:

class Counter {
  #count = 0

  increment() {
    this.#count++
  }
}

We now can’t access this value from the outside. Trying to access it will raise a syntax error.

This is part of the new class fields proposal, which you can use since Chrome 72 and Node 12.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment