Art Art - 4 months ago 15
Javascript Question

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?

Answer

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