Art
Art

Reputation: 24597

Why properties added via Object.defineProperty are not iterable in Javascript

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?

Upvotes: 4

Views: 867

Answers (3)

Peter Ajtai
Peter Ajtai

Reputation: 57715

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

Upvotes: 2

aaaaaaaaaaaa
aaaaaaaaaaaa

Reputation: 3700

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

Upvotes: 1

Pointy
Pointy

Reputation: 413976

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

Upvotes: 0

Related Questions