1

フルスクリーンと呼ばれるオブジェクトを作成し、そのオブジェクト内に方向と呼ばれる別のオブジェクトを作成しました。したがって、私のコードは次のようになります。

FullScreen = {
  directions: {
    prev: -1,
    next: 1
  }
}

しかし、オブジェクトの外部からFullScreen.directions.prevを設定し、prevの負の値の横にあるFullScreen.directions.nextを変更できるようにしたいです。これを行う方法はありますか?

4

3 に答える 3

4

If I understand the question correctly, it's as simple as this:

FullScreen.directions.prev = -42;
FullScreen.directions.next = -FullScreen.directions.prev;

It might be better, however, to encapsulate this logic in a function:

FullScreen = {
  directions: {
    prev: -1,
    next: 1,
    setPrev: function (value) {
        value = +value; // coerce to number
        this.prev = value;
        this.next = -value;
    }
  }
}

// then
FullScreen.direction.setPrev(-42);

You could get even fancier using the special get/set syntax:

FullScreen = {
  directions: {
    _prev: -1,
    _next: 1,
    get prev() {
        return this._prev;
    },
    set prev(value) {
        value = +value; // coerce to number
        this._prev = value;
        this._next = -value;
    },
    get next() {
        return this._next;
    }
  }
}

// then
FullScreen.direction.prev = -42;
// invokes the setter function behind the scenes, so that _next is also set
于 2012-05-22T15:48:35.060 に答える
0

これを自動的に実現するには、オブジェクトgetset関数を使用する必要がありdirectionsます。

理想的には、実際の値を含む個別の変数があり、プロパティの1つを使用するたびにその変数を変更しますが、その変数から計算された値を取得するsetたびに変更します。get

于 2012-05-22T15:49:56.010 に答える
0

次のようなことができます。

var directions = {
    current: 0,
    prev: function () {
        return -current;
    },
    next: function () {
        return current;
    }
};

そして、それを操作して、または値directions.currentの代わりに変更することができます。nextprev

于 2012-05-22T16:04:45.850 に答える