I created this object and it's properties:
var obj = {};
Object.defineProperty( obj, "value", {
value: true,
writable: false,
enumerable: true,
configurable: true
});
var name = "John";
Object.defineProperty( obj, "name", {
get: function(){ return name; },
set: function(value){ name = value; }
});
So then I call a for loop on them:
for ( var prop in obj ) {
console.log( prop );
}
Which according to my tutorial, should produce the following results:
value
name
But instead it only displays value. Why is name not showing up?
To execute this loop, the Start condition is checked. This is usually the initial value where the counting should start. Next, the Condition is tested; this test determines whether the loop should continue. If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed.
In JavaScript, the for-in loop is a basic control statement that allows you to loop through the properties of an object. The statements of code found within the loop body will be executed once for each property of the object.
The default value for enumerable
in defineProperty
is false
; non-enumerable properties do not show up in for…in
loops. (That's the whole point of the enumerable
flag.) If you add enumerable:true
into your second definition also, it will 'fix' it.
See some docs.
Because the name property is not defined as enumerable, set the name definition to
Object.defineProperty( obj, "name", {
enumerable: true,
get: function(){ return name; },
set: function(value){ name = value; }
});
and it will show up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With