JavaScript getter and setter

Nothing else to do, so here's a basic implementation of getter and setter in JavaScript:

function Test() {
  this.testProperty = 'Foo';

  this.__set = function(property, value) {
    var self = this;
    return self[property] = value;
  }

  this.__get = function(property) {
    var self = this;
    return self[property];
  }

}

Usage:

var myTest = new Test();
myTest.__set('testProperty', 'Baz');
alert(myTest.__get('testProperty')); // 'Baz'

Perfectly useless from a practical point of view, but still.

Leave a Reply

Note: Only a member of this blog may post a comment.