JS: Get Set Property
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 = { pp: 333 }; const xson = {}; Reflect.setPrototypeOf(xson, xdad); console.assert(xson.pp === 333); // from parent
Accessing Non-Existent Property Return “undefined”
console.assert({ a: 2 }.b === 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 = { kk: 3 }; // create object xson, with xdad as parent const xson = Object.create(xdad); xson.kk = 4; // check console.assert(Object.hasOwn(xson, "kk")); console.assert(xson.kk === 4); console.assert(xdad.kk === 3);