1 of 11

Private methods and accessors:

For Stage 3

Daniel Ehrenberg

Igalia

in partnership with Bloomberg

TC39 September 2017

2 of 11

Code sample

class Counter extends HTMLElement {� #xValue = 0;�� get #x() { return this.#xValue; }� set #x(value) {� this.#xValue = value; � window.requestAnimationFrame(

this.#render.bind(this));� }�� #clicked() {� this.#x++;� }��

constructor() {� super();� this.onclick = this.#clicked.bind(this);� }�� connectedCallback() { this.#render(); }�� #render() {� this.textContent = this.#x.toString();� }�}�window.customElements.define('num-counter', Counter);

3 of 11

Why?

  • Private methods encapsulate behavior
  • You can access private fields inside private methods

class Counter extends HTMLElement {� #x = 0;�

connectedCallback() {

this.#render();

}� #render() {� this.textContent =

this.#x.toString();� }�}��

4 of 11

Syntax

class Counter extends HTMLElement {� #x = 0;�

connectedCallback() { this.#render(); }�� #render() {� this.textContent = this.#x.toString();� }�}

  • Similar to ordinary methods
  • Easy to change public <-> private

5 of 11

Type checking the receiver

class C {� #foo() { alert("hi"); }� bar() {� this.#foo();� }

}�

C.prototype.bar.call();

⇒ TypeError

new C().bar.call();

⇒ alert

  • Analogous to a non-writable private field
  • Error thrown when reading the private method off an instance which doesn’t have it
  • Once you read it, no error for wrong receiver with .call()

6 of 11

Private accessors

class Counter extends HTMLElement {� #xValue = 0;� get #x() {

return this.#xValue;

}� set #x(value) {� this.#xValue = value; � }

}��

  • Analogous to private methods; why not?
  • # can apply to any class element
  • Useful for large classes

7 of 11

Instantiation order:�Methods before fields

class C {

#field = this.#method();� #method() { return 1; }� bar() { return this.#field }

}

new C().bar ⇒ 1

InstantiateInstanceElements

8 of 11

Specification updates

  • Rebased on top of private fields patch
  • Fix various typos 1 2

9 of 11

Community feedback

  • Skepticism about private fields design decisions bug
    • Use of # and not private
    • No reflection capabilities
    • FP vs OO
  • Friend/protected methods?
    • Symbols decorators presentation later
  • Strong use cases
    • Node, SalesForce, Bloomberg
  • Non-writable?

10 of 11

Implementation status

  • Babel implementation in progress PR
  • No native implementations or test262 tests yet

11 of 11

Stage 3 reviews

  • Reviewers:
    • Adam Klein -- +1
    • Bradley Farias -- +1
    • Waldemar Horwat -- +1
  • Editor?
  • Stage 3?