ES Class Fieldsのプライベートフィールドがハッシュな変態記法なのは何でなんだぜ?
プライベートフィールドがハッシュな変態記法なのは何でなんだぜ?
class Point {
#x;
#y;
constructor(x = 0, y = 0) {
#x = x;
#y = y;
}
get x() { return #x }
get y() { return #y }
area() {
return #x * #y;
// return this.#x * this.#y;
}
equals(p) {
return #x === p.#x && #y === p.#y;
}
toString() {
return `Point<${ #x },${ #y }>`;
}
}
Symbol
で事足りるので存在意義がないclass Foo {
#bar = 1;
}
const foo = new Foo();
foo.bar = 2; // Works!
class Bar extends Foo {
bar = 3; // Works!
}
private foo
じゃない理由this.foo
と呼び出したときにprivateかどうか不明なのでルックアップが走る// this.fooが参照されるたびに走る処理系の動きのイメージ(疑似コード)
if (
otherPoint instanceof Point &&
isNotSubClass(otherPoint, Point)
) {
return getPrivate(otherPoint, 'foo');
} else {
return otherPoint.foo;
}
this.foo
のような従来使われているシンタックスで参照させられないprivate foo
できても嬉しさ半分となるthis['#foo']
は禁止this#foo
じゃない理由
#
is the most beautiful!
@
: taken by ES Decorators_
, $
: breaking change%
, ^
, &
, ?
: ASI hazardWeakMap
でhard privateは実現可能だが、使いづらいfoo.equals(bar)
とか)WeakMap
は遅い (筆者注: ほんと?)hard private以外はDecoratorsを使えばいろいろできるんじゃないか?
this.#foo
しかないという結論