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. [see JS: Function Form vs Operator]

const jj = { dog: 3 };

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

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

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

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

if the property is a getter property, thisValue is passed to the getter function as this-binding. If not a getter property, thisValue is ignored.

// 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",
);