这是对象定义:
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
当我遍历对象时如何到达“键”?
您必须在属性描述符中明确声明您的属性是可枚举的。默认值为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);}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句