Search code examples
javascriptclosuresdefineproperty

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 || args === null) {
        return;
    }
    if (args.nickname !== undefined && args.nickname !== null) {
        _nickname = args.nickname;
    }

}

Object.defineProperty(Person.prototype, "nickname", {
    get : function () {
        return _nickname;
    }
});

var x = new Person({
        nickname : 'bob'
    });

console.log(x.nickname);

How should one go about accomplishing this? Is there a way of adding _nickname to the prototype of Person from within its function?


Solution

  • 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):

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