๐ธ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
// ๐ .babelrc
{
"presets": [
"env"
],
"plugins": [
"transform-runtime",
"@babel/plugin-proposal-class-properties", // โฎ โญ๏ธ ๅ ้ๅ
ฉๅ
"@babel/plugin-proposal-private-methods" // โฏ
],
"parserOpts": {
"plugins": [
"dynamicImport"
]
}
}
Last updated