简体   繁体   中英

How do i iterate over an object which used getter in javascript

Here's the object defination:

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

But i found i cannot iterate over this object by the way i want.

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

How could i reach "key" when i iterate over the object?

You have to state explicitly at the property descriptor that your property is enumerable. The default value is false. This is the reason why you don't get it when you use the for..in . According to MDN

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

Regarding the enumerable property, as it is stated here :

enumerable

true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to 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);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM