Is there a way to add _nickname to the Person prototype from its function?
If you mean the constructor of Person , I am sure (although, in my opinion, it does not look very elegant):
var Person = function (args) { var _nickname = ''; if (args === undefined || args === null) { return; } if (args.nickname !== undefined && args.nickname !== null) { _nickname = args.nickname; } Object.defineProperty(this, "nickname", { get : function () { return _nickname; } }); } var x = new Person({ nickname : 'bob' }); console.log(x.nickname);
http://jsfiddle.net/JEbds/
In this case, your getter is just another closure, so it has access to _nickname . And this is not on the prototype anymore, you need your own property to accomplish this.
source share