JS: Reflect.get
New in JS2015.
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.
This function is similar to the syntax
obj[key]
, but in a function form. Function form lets you easily manipulate it at run-time.const jj = { k: 3 }; console.log(Reflect.get(jj, "k") === 3); // if property key is not found, return undefined console.log(Reflect.get(jj, "h") === undefined);
// Reflect.get looks up prototype chain const xx = { p: 3 }; const yy = {}; Object.setPrototypeOf(yy, xx); // x is parent of y console.log(Reflect.get(yy, "p") === 3);
Reflect.get(obj, key , thisValue)
-
thisValue is passed as this Binding to a getter property call.
〔see Getter Setter Properties〕
Getter Property and ThisValue 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", ); // prints "getter called"
〔see Getter Setter Properties〕