JS: Reflect.get

By Xah Lee. Date: . Last updated: .

New in ES2015.

Similar to obj[key].

Get the value of a property, own property or in prototype chain.

If key is not found, return value is undefined.

If obj is not object, throw a TypeError exception.

receiver is passed as this value to a getter property call.

[see JS: Getter/Setter Properties]

[see JS: “this” Binding]

const u = {p:3};

console.log( Reflect.get ( u , "p" ) === 3 ); // true

// if property key is not found, return undefined just like obj.key
console.log( Reflect.get ( u , "h" ) === undefined ); // true
// Reflect.get will traverse the prototype chain to find property

const x = {p:3};

const y = Object.create (x);
// x is parent of y

console.log (
    Reflect.get ( x, "p" ) === 3
); // true

[see JS: Access Property]

Getter Property and Receiver Example

// create a object with 2 properties: p1 and p2. The p2 is a getter property.
const xx = {
    p1: 1,
    get p2() {
        console.log("getter called");
        return this.p1;
    }
};

// create some unrelated object with key p1
const yy = {p1:"wow"};

console.log (
    Reflect.get ( xx , "p2" , yy) === "wow"
); // true
// prints "getter called"

[see JS: Getter/Setter Properties]

Reference

ECMAScript® 2016 Language Specification#sec-reflect.get

back to JS: Reflect Object

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon