JS: Reflect.get

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Reflect.get(obj, key)
Return the value of a property, own property or in Prototype Chain.
  • If key is not found, return undefined.
  • If obj is not Object Type object, throw a TypeError exception.

🟢 TIP: This function is similar to the syntax obj[key], but in a function form. Function form lets you manipulate expressions at run-time.

const jj = { k: 3 };

console.assert(Reflect.get(jj, "k") === 3);

// if property key is not found, return undefined
console.assert(Reflect.get(jj, "h") === undefined);
// Reflect.get looks up prototype chain

const xdad = { p: 3 };
const xson = {};
Reflect.setPrototypeOf(xson, xdad);

console.assert(Reflect.get(xson, "p") === 3);
Reflect.get(obj, key , thisValue)

thisValue is passed as this (binding) to a getter property call.

// create a object with 2 properties: real_color and xcolor. The xcolor is a getter property.
const xx = {
 real_color: "red",
 get xcolor() {
  return this.real_color;
 },
};

// create some unrelated object with key real_color
const yy = { real_color: "blue" };

console.assert(Reflect.get(xx, "xcolor") === "red");

console.assert(Reflect.get(xx, "xcolor", yy) === "blue");

JavaScript. Access Properties