JavaScript: Getter/Setter Properties with native JavaScript
The following is a rudimentary 'iterator' (not to be confused with JavaScript 1.7 iterator) that contains 'next' and 'previous' getter properties that range between 0 and 100, and the 'force' setter forces the iterator's value.
<script>
var I = {
get next() {
return this.counter < 100 ? ++this.counter : this.counter;
},
get previous() {
return this.counter > 0 ? --this.counter : this.counter;
},
set forced(c) {
this.counter = c;
},
counter: 0
}
alert(I.next);
alert(I.previous);
I.forced = 4;
alert(I.next);
//obviously there's no member hiding in this context, so you could even set I.counter = 4, however this setter could be home to data sanitization etc.
</script>