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

ill*_*rix 3 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];
    }
};
Run Code Online (Sandbox Code Playgroud)

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

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

当我遍历对象时,我怎么能达到"密钥"?

Chr*_*tos 5

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

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

关于枚举属性,因为它是说在这里:

枚举

当且仅当在枚举相应对象的属性期间显示此属性时,才返回true.默认为false.

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);}
Run Code Online (Sandbox Code Playgroud)