🔸private member
JS ⟩ value ⟩ object ⟩ class ⟩ member ⟩ private
private members are not inherited❗
class A {
// ⭐️ private members // # means "private"
#a; // this.#a = undefined
#b = 0; // this.#b = 0
get #c() { return 0 } // this.#c (private getter)
#d() { ... } // this.#d() (private method)
// ⭐️ private static members
// (accessable only within the class body)
static #staticProp; // A.#staticProp
static get #CONST() { return 0 } // A.#CONST
static #staticMethod() { ... } // A.#staticMethod()
}
never use "this" to access a private static field,
always use the direct class name.
👉 📗 2ality.com ⟩ ECMAScript proposal: private class fields
private/protected members (duplicate?)
const {log} = console;
class A {
// ⭐️ `#` is part of the name❗️
// ⭐️ private instance members
#age; // declaration only
#n = 3; // with definition
// const #constant = 6; // no private constant❓
// this.#constant2
get #constant2() { return 2; } // workaround
#steal(something) { }
// ⭐️ private static members
// -----------------------
// ⭐️ only the class which defines the private static field
// can access the field.
static #TOP_SECRET;
static #total() { return 10 }
// A.constant
static get #constant(){ return 6; } // static constant
// init
constructor() {
this.#age = 42;
log(`n = ${this.#n}, total: ${A.#total()}`);
log(`static A.constant: ${A.#constant}`);
log(`instance constant: ${this.#constant2}`);
}
// this.age
get age(){ return this.#age }
}// end: class A
// test run
let a = new A(); // "n = 3, total: 10"
// "A.constant: 6"
// "instance constant: 2"
log(a.age); // 42
MDN ⟩
Classes ⟩ Private class features ⭐️
Guides ⟩ Working with private class features
Web Workers ⟩ console.assert()
console ⟩ Outputting text to the console
GitHub ⟩ tc39/proposal-destructuring-private ⭐️
TC39 (spec) ⟩ destructuring private fields (stage 2 draft, as of 2022/03/18)
Node.js ⟩
assert.throws(fn[, error][, message])
destructuring private members not supported currently❓
(stage 2 draft, as of 2022/03/18)
const {#prop: prop} = this;
// ^^^^^ (⛔ SyntaxError: Unexpected identifier)
supporting environments
Last updated
Was this helpful?