My aim to to create an object in Javascript where I can easily just go block.red = 128;
or block.red += 5
. Which could easily be done using this.red
inside the object, but I want my object also be able to do which is stumping me is to ensure that the red value falls within the accepted range (i.e. not above 255 and not below 0).
I've had a bit of a look around, and one thing I thought might work was encapsulation. The problem being then is that I can't use the compound assignment operator. Obviously this isn't the end of the world, but I would like to know if there are any solutions that I haven't thought up.
function colours(r, g, b) {
_r = r;
_g = g;
_b = b;
this.red = red;
function red(value) {
if (value == undefined) {
return _r;
} else {
if (value < 0) {
_r = 0;
} else if (value > 255) {
_r = 255;
} else {
_r = value;
}
}
}
}
// tests
colours(240, 120, 60);
alert(red());
red(120);
alert(red());
red(360);
alert(red());
// works up to here
red() -= 30;
alert(red());
So do you have any ideas of how I can keep the compound assignment operator while still ensuring the red value stays within range?