Using Object.DefineProperty and accessing a variable in private scope

▼魔方 西西 提交于 2020-01-24 06:23:13

问题


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?


回答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):

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.



来源:https://stackoverflow.com/questions/18368580/using-object-defineproperty-and-accessing-a-variable-in-private-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!