JS: Reading/Writing Property and Prototype Chain
Reading property goes up the prototype chain
When a property of a object is looked up (e.g. obj.color), JavaScript first look at the object to see if it has that property, if not, it lookup its parent, and repeat, until a property is found or no more
parent.
const xdad = { dog: 333 }; const xson = {}; Reflect.setPrototypeOf(xson, xdad); console.assert(xson.dog === 333); // from parent
Accessing non-existent property return “undefined”
console.assert({ dog: 2 }.cat === undefined);
Setting property never go up prototype chain
When setting a value to a key, if the object has the property, its value is modified. If the object does not have the property, its created.
// setting a property never go up prototype chain const xdad = { dog: 3 }; // create object xson, with xdad as parent const xson = Object.create(xdad); xson.dog = 4; // check console.assert(Object.hasOwn(xson, "dog")); console.assert(xson.dog === 4); console.assert(xdad.dog === 3);