「JavaScript/クラス」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
344 行
Test.n = 123
</syntaxhighlight>
 
=== プライヴェートフィールド ===
クラスのインスタンスには、クラスの外からはプロパティアクセスのできないプライヴェートフィールドを設けることができます。
;[https://paiza.io/projects/9Qxuwy_MW8fArHGY3eYa3g?language=javascript プライヴェートフィールドの使用例]:<syntaxhighlight lang="javascript" highlight="2,4,6" line>
class ClassWithPrivateField {
#x
constructor(x = 42) {
this.#x = x
}
value(c){ return this.#x }
static getValue(c){ return c.#x }
}
 
var x = new ClassWithPrivateField()
var y = new ClassWithPrivateField(195)
 
console.log(x.value())
console.log(y.value())
console.log(ClassWithPrivateField.getValue(x))
f = ClassWithPrivateField.getValue
console.log(f(y))
</syntaxhighlight>
;実行結果:<syntaxhighlight lang="text">
42
195
42
195
</syntaxhighlight>
:{{code|#x}}はプライヴェートフィールドの宣言で、#x にはメソッドのthisを介して、{{code|this.#x}}の様に参照します。
:トリッキーですが、staticメソッドからもプライヴェートフィールドを参照でき、staticメソッドの値を使った予備しでもまたプライヴェートフィールドを参照できます。
 
=== 脚注 ===