Java Reference
In-Depth Information
This uses the
set()
method of the property descriptor. The argument of this is the value
that's assigned to the property. In the example this value is simply returned, implying that
the value of the
sillyString()
property has been set to the string
"Hello"
. We can
check the value using the dot notation:
example.sillyString;
<< "Craaazy!"
This calls the
get()
method, which ignores the value returned by the
set()
method and
returns the string
"Craaazy!"
, regardless of the value that was assigned to the property.
These methods give you much more power in controlling the way property assignment
works; however, they should be used sparingly and with care, as changing the expected be-
havior of an assignment has the potential to cause a lot of confusion.
The
get
and
set
property descriptors are particularly useful for controlling the getting
and setting of properties in constructor functions. In the example that follows, the
Dice()
constructor function has been rewritten so that
sides
is now a private variable. We can
then use the
sides
property to create a
get
function that will return a description of the
number of sides, rather than just the actual number and a
set
function that prohibits a non-
positive number of sides to be set:
var Dice = function() {
"use strict";
var sides = 6;
Object.defineProperty(this, 'sides', {
get: function() {
return "This dice has " + sides + " sides";
},
set: function(value) {
if(value > 0) {
sides = value;
return sides;
} else {
throw new Error("The number of sides must be
positive");
}
