且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript属性值依赖于其他属性

更新时间:2023-02-03 20:40:09

如果我正确理解了这个问题,就像这样简单:

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