Private methods and accessors:
For Stage 3
Daniel Ehrenberg
Igalia
in partnership with Bloomberg
TC39 September 2017
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);
Why?
class Counter extends HTMLElement {� #x = 0;�
connectedCallback() {
this.#render();
}� #render() {� this.textContent =
this.#x.toString();� }�}��
Syntax
class Counter extends HTMLElement {� #x = 0;�
connectedCallback() { this.#render(); }�� #render() {� this.textContent = this.#x.toString();� }�}
Type checking the receiver
class C {� #foo() { alert("hi"); }� bar() {� this.#foo();� }
}�
C.prototype.bar.call();
⇒ TypeError
new C().bar.call();
⇒ alert�
Private accessors
class Counter extends HTMLElement {� #xValue = 0;� get #x() {
return this.#xValue;
}� set #x(value) {� this.#xValue = value; � }
}��
Instantiation order:�Methods before fields
class C {
#field = this.#method();� #method() { return 1; }� bar() { return this.#field }
}
new C().bar ⇒ 1
Community feedback
Implementation status
Stage 3 reviews