◆◆◆ 翻訳中 ◆◆◆
このページは翻訳中です。
翻訳作業に参加する場合は、履歴にある翻訳者と連絡·調整してください。
概要
オブジェクトの値を得たいとき呼ばれる関数にオブジェクトプロパティを結び付けます。
書式
{get prop() { . . . } }
パラメータ
prop- 与えられた関数に繋ぐプロパティの名前
説明
時として、動的に計算した値を返すプロパティにアクセスを許可したほうが望ましい場合や、明示的なメソッドを呼び出すことなく内部変数の状態を反映させたいときがあります。Javascriptでは、getterを使ってこれを行うことが可能です。プロパティのタイプを作るのと同時にgetterとsetterを使うことは可能ですが、getterにプロパティ自身とそれが持つ値を同時に返させることはできません。
JavaScript 1.8.5 における注記
JavaScript 1.8.5から、get 演算子に以下の追加機能があります:
- 数値か文字列かを識別するための識別子を持つことができます。
- パラメーターの個数は正確にゼロ個でなければなりませんmust have exactly zero parameters (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information);
- must not appear in an object literal with another
getor with a data entry for the same property ({ get x() { }, get x() { } }and{ x: ..., get x() { } }are forbidden).
A getter can be removed using the delete operator.
Examples
Defining a getter with the get operator
This will create a pseudo-property latest of object o that will return the most recent entry into o.log:
var o = {
get latest () {
if (this.log.length > 0) {
return this.log[this.log.length - 1];
}
else {
return null;
}
},
log: []
}
Note that attempting to assign a value to latest will not change it.
Deleting a getter using the delete operator
delete o.latest;
See also
deleteset__defineGetter____defineSetter__- Defining Getters and Setters in JavaScript Guide
Mozilla Developer Network