我如何迭代在javascript中使用getter的对象

时间:2017-01-31 06:48:14

标签: javascript

这是对象定义:

var Vars = new function(){
    var that = this;
    this.assign = function(name) {
        var realValue = undefined;
        Object.defineProperty(that, name, {
            configurable: true,
            get: function() {
                //console.log("Get");    do something...
                return realValue; 
            },
            set: function(v) {
                //console.log("Set");    do something...
                realValue = v;
            }
        });
    }
    this.destroy = function(name) {
        return delete that[name];
    }
};

但是我发现我不能按照我想要的方式迭代这个对象。

>> Vars.assign("key")
<- undefined
>> Vars.key = 1
<- 1
>> Vars.key
<- 1
>> for(var i in Vars){console.log(i);}
assign 
destroy 
<- undefined

当我遍历对象时,我怎么能达到“key”?

1 个答案:

答案 0 :(得分:5)

您必须在属性描述符中明确声明您的属性是可枚举的。默认值为false。这就是您在使用for..in时没有得到它的原因。根据{{​​3}}

  

for ... in语句迭代了一个的可枚举属性   对象,以任意顺序。对于每个不同的属性,语句都可以   被执行。

关于可枚举属性,如MDN所述:

  

可枚举

     

当且仅当此属性在此期间显示时才显示   枚举相应对象的属性。默认为   假的。

var Vars = new function(){
    var that = this;
    this.assign = function(name) {
        var realValue = undefined;
        Object.defineProperty(that, name, {
            configurable: true,
            // This is the missing line
            enumerable: true,
            get: function() {
                //console.log("Get");    do something...
                return realValue; 
            },
            set: function(v) {
                //console.log("Set");    do something...
                realValue = v;
            }
        });
    }
    this.destroy = function(name) {
        return delete that.Local[name];
    }
};
Vars.assign("key");
for(var i in Vars){console.log(i);}

相关问题