javascript property value dependent of other property

I made an object called Fullscreen, and within the object another object called directions. so my code looks like this:

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

but i want to be able to set FullScreen.directions.prev from outside the object, and change FullScreen.directions.next to the negative value of the prev. any ideas how to do this?

Answers:

Answer

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
Answer

To make this happen automagically you'd need to use get and set functions on the directions object.

Ideally you'll have a separate variable which contains the actual value, and each time you set one of the properties, you change that variable, but each time you get you retrieve the value calculated from that variable.

Answer

You can do something like this:

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

And then you can interact with it and modify your directions.current instead of either of next or prev values.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.