Created
December 5, 2012 22:43
-
-
Save benbuckman/4220190 to your computer and use it in GitHub Desktop.
JS getter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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