![](/img/trans.png)
[英]How do I iterate over the properties of an Object's prototype in JavaScript?
[英]How do i iterate over an object which used getter in 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
当我迭代对象时,我怎么能到达“关键”?
您必须在属性描述符中明确声明您的属性是可枚举的。 默认值为假。 这就是为什么您在使用for..in
时没有得到它的原因。 根据MDN
for...in 语句以任意顺序迭代对象的可枚举属性。 对于每个不同的属性,都可以执行语句。
关于可枚举属性,正如此处所述:
可枚举的
当且仅当在枚举相应对象的属性期间出现此属性时才为 true。 默认为假。
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);}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.