Property Descriptors
Video
JavaScript Notes
JavaScript
// Property Descriptors Methods and Usage
Object.defineProperty(obj, propName, { })
Object.defineProperties(obj, props)
Object.getOwnPropertyNames(obj)
Object.getOwnPropertyDescriptor(obj, prop)
Object.getOwnPropertyDescriptors(obj)
Object.keys(obj) - list of enumerable properties
Object.values(obj) - list of enumerable properties
obj.propertyIsEnumerable(prop)
obj.hasOwnProperty(prop)
Objects can be
1. Extensible - new properties added
2. Frozen - props cannot be changed in anyway
3. Sealed - props cannot be deleted or configured but are still writable
Object PROPERTIES can be
1. Writable - change the value
2. Enumerable - seen through a for…in loop
3. Configurable - change the property descriptors
Object.isExtensible(obj)
Object.isFrozen(obj)
Object.isSealed(obj)
Object.preventExtensions(obj)
Object.freeze(obj)
Object.seal(obj)
Descriptor Groups
DATA ACCESSOR
value get
writable set
configurable configurable
enumerable enumerable
**************************************************/
let log = console.log;
let obj = {
name: 'Bob',
age: 45
};
for (let prop in obj){ // list all enumerable properties in the object
log(prop);
};
Object.defineProperty(obj, 'test', {
value: 'Shagadelic',
writable: true,
configurable: true,
enumerable: false // like a ‘behind the scenes’ property
} );
Object.defineProperty(obj, 'frank', {
get: ( ) => this.value,
set: (_val) => {
this.value = _val + " baby!";
},
configurable: true,
enumerable: true
} );
log(obj, obj.test, obj.frank); // obj.frank returns undefined as no value has been set
obj.frank = 'Shagadelic';
log(obj.frank); // returns Shagadelic baby!
Feedback
Submit and view feedback