tags:

views:

44

answers:

3

Consider this code:

var a = {
    get aa() {
        return 'aa';
    }
};

Object.defineProperty(
    a,
    'bb',
    {
        get: function() {
            return 'bb';
        }
    }
);

for(p in a) {
    sys.puts(p + ': ' + a[p]);
}

The output is:

aa: aa

However property bb is perfectly accessible and working.

Why 'bb' is not visible in for..in loop?

A: 

The boolean fields of an object property's "meta-properties" all default to false, including the enumerable property.

Pointy
A: 

Because this behaviour may be practical for adding in meta properties. The behaviour can be changed by setting the enumerable property. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty

eBusiness
+1  A: 

You have to set enumerable to true.

(You could also give getOwnPropertyNames() a try,but I'm not sure how cross browser that is.)

var a = {
    get aa() {
        return 'aa';
    }
}, arr = [];

Object.defineProperty(
    a,
    'bb',
    {
        get: function() {
            return 'bb';
        },
        enumerable: true
    }
);

for(p in a) {
    arr.push(p + ': ' + a[p]);
}
alert(arr.join("\n"));

Try it out with this jsFiddle

Peter Ajtai