JS: Get Set Property

By Xah Lee. Date: . Last updated: .

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 aa = { a: 3 };
const bb = {};
Reflect.setPrototypeOf(bb, aa);

console.log(bb.a === 3);
// from parent

// bb has no keys
console.log( Reflect.ownKeys( bb ).length === 0 );

Accessing Non-Existent Property Return β€œundefined”

{a:2}.b === undefined

Setting Property Never Touches 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 will not touch prototype chain

const xx = { kk: 3 };

// create object yy, with xx as parent
const yy = Object.create(xx);

yy.kk = 4;

console.log(xx.kk === 3);

JavaScript, Property

BUY Ξ£JS JavaScript in Depth