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しかないという結論