动态Getter和Setter - 为什么这不起作用?

Kri*_*iem 2 javascript dynamic getter-setter

我正在尝试创建一个动态构建自己的getter和setter的对象:

function Person( properties ) { // 'properties' is an object literal

    this._private = properties; // private by convention

    for ( key in this._private ) {

        this[key] = function() {

            return this._private[key];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望,这会产生这样的东西:

var jack = new Person({

    working:true,
    age:33,
    gender:'male'
});

jack.working() --> true
jack.age() --> 33
jack.gender() --> 'male'
Run Code Online (Sandbox Code Playgroud)

问题是,它总是返回'男性',如下所示:

jack.working() --> 'male'
jack.age() --> 'male'
jack.gender() --> 'male'
Run Code Online (Sandbox Code Playgroud)

我错过了什么?哦,这只是一个概念证明.我知道这不是用JavaScript创建getter和setter的完美解决方案.

And*_*ker 7

你有一个经典的范围问题.创建一个新函数来创建范围key:

function Person(properties) { // 'properties' is an object literal
    var key;

    this._private = properties; // private by convention
    this.buildGetter = function (key) {
        this[key] = function () {
            return this._private[key];
        }
    };
    for (key in this._private) {
        this.buildGetter(key);
    }
}
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/SEujb/