Skip to content

Instantly share code, notes, and snippets.

@benbuckman
Created December 5, 2012 22:43
Show Gist options
  • Save benbuckman/4220190 to your computer and use it in GitHub Desktop.
Save benbuckman/4220190 to your computer and use it in GitHub Desktop.
JS getter example
function Client(){
this.subClient = new SubClient();
};
function SubClient(){
this.numConnections = 0;
this.status = 'OK';
};
// getting error,
// TypeError: Invalid property. A property cannot both have accessors and be writable or have a value, #<Object>
['numConnections', 'status'].forEach(function(staticProp){
Object.defineProperty(Client.prototype, staticProp, {
enumerable: true,
writable: true,
get: function(){
return this.subClient[staticProp];
},
set: function(newVal){
return this.subClient[staticProp] = newVal;
}
});
});
var assert = require('assert');
var util = require('util');
var cl = new Client();
assert.equal(cl.numConnections, 0);
assert.equal(cl.status, 'OK');
cl.subClient.numConnections++;
cl.subClient.status = 'BROKEN';
assert.equal(cl.numConnections, 1);
assert.equal(cl.status, 'BROKEN');
// console.log(util.inspect(cl,true,10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment