A property descriptor specifies how a JavaScript property behaves. Use Object.defineProperty to control whether it can be changed, deleted, or enumerated, and to define its value or accessors. section 7.3.1
Descriptors configure these property behaviors:
- configurable controls whether the descriptor can be changed or the property deleted; enumerable controls whether it appears in a for-in loop. section 7.3.1
- value sets the property value, and writable controls whether assignment can change it. section 7.3.1
- get and set define functions called on property access and assignment; they cannot be combined with value and writable. section 7.3.1
Listing 7.9. Configuring properties
var ninja = {}; #A
ninja.name = "Yoshi"; #A
ninja.weapon = "kusarigama"; #A
Object.defineProperty(ninja, "sneaky", { #B
configurable: false, #B
enumerable: false, #B
value: true, #B
writable: true #B
}); #B
assert("sneaky" in ninja, "We can access the new property");
for(let prop in ninja){ #C
assert(prop !== undefined, "An enumerated property: " + prop); #C
} #C
See an example that defines an accessible but non-enumerable property. section 7.3.1
Descriptors also help repair a prototype reassignment: after Ninja.prototype is set to a Person instance, define a non-enumerable constructor property pointing back to Ninja. section 7.3.1 section 7.3
Listing 7.10. Fixing the constructor property problem
function Person(){}
Person.prototype.dance = function(){};
function Ninja(){}
Ninja.prototype = new Person();
Object.defineProperty(Ninja.prototype, "constructor", { #A
enumerable: false, #A
value: Ninja, #A
writable: true #A
}); #A
var ninja = new Ninja();
assert(ninja.constructor === Ninja, #B
"Connection from ninja instances to Ninja constructor #B
reestablished!"); #B
for(let prop in Ninja.prototype){ #C
assert(prop === "dance", "The only enumerable property is dance!"); #C
} #C
The example restores the constructor link while keeping it out of enumeration. section 7.3.1
Accessor functions can also react to reads and writes, for example to validate values, log changes, or update a user interface. section 8.1
