LoginSignup
11
12

More than 5 years have passed since last update.

変数の値の変更・取得時に任意の処理を実行する

Last updated at Posted at 2014-09-04
player = new Player();
player.point = 1;

など、変数の値を変更したときに同時に任意の処理を実行したい場合

function Player() {
}
Player.prototype = 
{
  get point() {
    // 任意の処理
    return this._point;
  },
  set point(value) {
    // 任意の処理
    this._point = value;
  },
}

このようにクラスのメソッドとして get point(), set point(value) を定義すると下記のようにメソッドが呼び出されます。

player = new Player();
a = player.point; // -> a = get point();
player.point = b; // -> set point(b);

_point は実際に値を保存するために宣言した変数です。
なので、point と _point は全くの別物です。
上の例で _point として宣言している変数の名前はフックしたい変数名と異なる名前ならば何でも大丈夫です。(ただ、読みやすさ的には変数が紐づいていることを明示する名前が良いと思います)



変数の値を変更した際に、特定の要素のテキストも自動的に変更したいときなどに便利です。

function Player() {
  this._point = 0;
}
Player.prototype = 
{
  get point() {
    return this._point;
  },
  set point(newPoint) {
    this._point = newPoint;
    // id = js_my_point の要素のテキストを同時に変更
    document.getElementById('js_my_point').innerText = this.point;
  },
}

(補足)
フックしないで値を変更・取得したい場合は this._point を使えば良いです。

11
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12