Object.defineProperty
suggest changeIt allows us to define a property in an existing object using a property descriptor.
const obj = { };
Object.defineProperty(obj, 'foo', { value: 'foo' });
console.log(obj.foo);
Console output
foo
If writable, enumerable, or configurable is omitted, it defaults to false. The first example’s foo is therefore not writable, not enumerable, and not configurable. The descriptor fields are:
Object.defineProperty(obj, 'nameOfTheProperty', {
value: valueOfTheProperty,
writable: true, // if false, the property is read-only
configurable : true, // true means the property can be changed later
enumerable : true // true means property can be enumerated such as in a for..in loop
});
Object.defineProperties allows you to define multiple properties at a time.
const obj = {};
Object.defineProperties(obj, {
property1: {
value: true,
writable: true
},
property2: {
value: 'Hello',
writable: false
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents