Skip to content

Instantly share code, notes, and snippets.

@rob-blackbourn
Last active August 29, 2015 14:22
Show Gist options
  • Save rob-blackbourn/f324c62dec270d03024d to your computer and use it in GitHub Desktop.
Save rob-blackbourn/f324c62dec270d03024d to your computer and use it in GitHub Desktop.
JavaScript Property Getters and Setters

JavaScript Property Getters and Setters

The attached code shows how to create getters and setters for a JavaScript object against the object prototype.

The example shows a situation where I want to store the underlying data (an RGBA colour) as an array, but wish to allow access throough getters and setters: i.e. colour.red = 255.

Running the example produces the following result:

red=255, green=128, blue=16, alpha=100
red=255
green=128
blue=16
alpha=100
red=0, green=128, blue=16, alpha=100
red=0
function Colour(red, green, blue, alpha) {
this.value = [red, green, blue, alpha];
}
Object.defineProperty(Colour.prototype, "red", {
get: function () {
return this.value[0];
},
set: function (x) {
this.value[0] = x;
}
});
Object.defineProperty(Colour.prototype, "green", {
get: function () {
return this.value[1];
},
set: function (x) {
this.value[1] = x;
}
});
Object.defineProperty(Colour.prototype, "blue", {
get: function () {
return this.value[2];
},
set: function (x) {
this.value[2] = x;
}
});
Object.defineProperty(Colour.prototype, "alpha", {
get: function () {
return this.value[3];
},
set: function (x) {
this.value[3] = x;
}
});
Colour.prototype.toString = function() {
return "red=" + this.red + ", green=" + this.green + ", blue=" + this.blue + ", alpha=" + this.alpha;
};
var colour = new Colour(255, 128, 16, 100);
console.log(colour.toString());
console.log("red=" + colour.red);
console.log("green=" + colour.green);
console.log("blue=" + colour.blue);
console.log("alpha=" + colour.alpha);
colour.red = 0;
console.log(colour.toString());
console.log("red=" + colour.red);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment