by Vaidehi Joshi (@vaidehijoshi)
Creator of BaseCS
let cat = {};
We can think about properties as variables assigned to the object. Each property has a property descriptor, which holds internal metadata for each property on a JS object. Property descriptors are themselves javascript objects.
We can manipulate an object using the configuration of its descriptors.
cat.sound;
cat["sound"];
Object.getOwnPropertyDescriptor(cat, "sound");
// {
// value: "meow",
// writable: true,
// enumerable: true,
// configurable: true
// }
Has a value, which may be editable (writable
).
cat.sound = function() {
return "hi!";
};
cat.sound = function() {
return "I can write over this property!";
};
value
and writable
property descriptors do not exist on Getter and Setters.
function Cat(name) {
this.name = name;
}
Cat.prototype = {
get sound() {
return `Hi, my name is ${this.name}`;
}
};
const alfred = new Cat("alfred");
alfred.sound; // "Hi, my name is Alfred"
Object.getOwnPropertyDescriptor(cat, "sound"); // { get: f(), set: undefined, enumerable: true, configurable: true }
These show up on every property descriptors.
enumerable
: Will this show up when we enumerate over the object? (e.g. in a loop or using Object.keys()
)
configurable
: Can this property be modified or deleted? If false
, it cannot be deleted or changed.
By default, all Objects are extensible — new properties can be added to the object
Object.seal()
: Don't let new properties be added or existing ones removed, but allow existing properties to be altered
Object.freeze()
: Don't let properties be added, removed, or changed
Gotchas with Object.freeze()
:
- A getter's value isn't going to be frozen
- Properties with other javascript objects as their value also need to be explicitly frozen (e.g. deep freeze 🥶)
An object's parent's properties are not emumerable. Only its own properties are enumerable.