In JavaScript you can define getters and setters by using Object.defineProperty(). I am wondering if it is possible to extend or use the prototype of this to extend its functionality. Here is an example:
I start off a variable called color:
Object.defineProperty(window, 'color', {
get: function() {
return [_color.red,_color.green,_color.blue,_color.alpha];
},
set: function(val) {
_color.red = val[0];
_color.green = val[1];
_color.blue = val[2];
_color.alpha = val[3];
}
});
This allows for me to both set and get the color by passing rgba arrays to and from the variables. Here is how I would use this:
color = [0,127,255,255];
alert(color);
//alerts [0,127,255,255]
Now I also want to be able to edit these variables through accessing each variable individually.
color.r = 255;
alert(color);
//alerts [255,127,255,255]
I am at an impasse at this moment because I don’t know what I can do to create this. I would think either using color.prototype.r or something similar would work, but I can’t get it to. Is it possible to do something like this?
You have to create an interim object extended from array to do it specifically.
Here you go:
Hope it works! 😀