Skip to content Skip to sidebar Skip to footer

Using Object.defineproperty And Accessing A Variable In Private Scope

The following doesn't work, from my getter, I can't see _nickname defined in the 'class' Person. var Person = function (args) { var _nickname = ''; if (args === undefined

Solution 1:

Is there a way of adding _nickname to the prototype of Person from within its function?

If you mean the Person constructor, sure (although in my opinion it doesn't look very elegant):

varPerson = 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 = newPerson({
    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 it's not on the prototype anymore, you need an own property to accomplish that.

Post a Comment for "Using Object.defineproperty And Accessing A Variable In Private Scope"