プロパティーの自動変更



0   名前: きゅーぴー : 2005/05/08 16:40
画像を表示して、その位置などを参照したりコントロールするための
プロパティーを持ったクラスを作りたいのですが、

function hoge(){
  this.left = 0; // 左座標
  this.top = 0; // 上座標
  this.width = 0; // 幅
  this.height = 0; // 高さ
  this.bottom = 0; // 下座標
  this.right = 0; // 右座標
}
var foo = new hoge();
foo.left = 10;
foo.width = 30;

のようにプロパティーを変更した場合、
画像の下側や右側の座標を取得するのに、

foo.bottom = foo.top + foo.height;
foo.right = foo.left + foo.width;

と毎回計算しなくても .bottom や .right の座標を参照したとき、
もしくは .left や .width などを変更すると
自動的に上記の計算を行うような方法はありませんでしょうか?

1   名前: Pid : 2005/05/08 16:40
メソッドを作るのはどうでしょうか。たとえば,

// left を設定すると自動的に right を算出する
hoge.prototype.setLeft = function(n) {
  this.left = n;
  this.right = this.left + this.width;
}

// top を設定すると自動的に bottom を算出する
hoge.prototype.setTop = functoin(n) {
  this.top = n;
  this.bottom = this.top + this.height;
}

var foo = new hoge;
foo.setLeft(10);
foo.setTop(5);

など。

※なお,厳密には JavaScript にクラスはありません。

2   名前: きゅーぴー : 2005/05/08 16:40
できれば hoge の中で処理できればと思っていましたが、
目的を達成できました。ありがとうございました。

一覧へ戻る