An accessor method provides controlled access to an object’s state or properties. A getter runs when a matching property is read; a setter runs when it is assigned. Getters can calculate values on demand, while setters can validate or log updates. section 8.3
A getter can also expose closure-held state without making the state variable directly accessible. In a constructor, an inner method can read that variable while another method controls how it changes. section 5.2.1
Reading closure-held state
A Ninja constructor keeps a feints counter in a local variable. Its getFeints method returns the count, while feint increments it; callers can read the count but cannot access the variable directly. section 5.2.1
Listing 5.3. Using closures to approximate private variables
function Ninja() { #A
var feints = 0; #B
this.getFeints = function(){ #C
return feints; #c
}; #C
this.feint = function(){ #D
feints++; #D
}; #D
}
var ninja1 = new Ninja(); #E
ninja1.feint(); #F
assert(ninja1.feints === undefined, #G
"And the private data is inaccessible to us."); #G
assert(ninja1.getFeints()=== 1, #H
"We're able to access the internal feint count."); #H
var ninja2 = new Ninja(); #I
assert(ninja2.getFeints()=== 0, #I
"The second ninja object gets its own feints variable."); #I
See the constructor, getter, and increment method working together to approximate private state. section 5.2.1












