2

我正在尝试创建一个动态构建自己的 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];
        }
    }
}

我希望,这会创造出这样的东西:

var jack = new Person({

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

jack.working() --> true
jack.age() --> 33
jack.gender() --> 'male'

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

jack.working() --> 'male'
jack.age() --> 'male'
jack.gender() --> 'male'

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

4

2 回答 2

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);
    }
}

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

于 2012-11-27T20:36:58.070 回答
3

每个人都说 eval 是邪恶的,但有时它是无法避免的:

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

    this._private = properties; // private by convention

    for ( key in this._private ) {

        eval("this[key] = function() { return this._private['"+key.toString()+"'];}");
    }
}

jsFiddle:http: //jsfiddle.net/pitaj/9sWbe/1/

于 2012-11-27T20:51:41.180 回答