Search⌘ K

Purpose of Reflect: Exploring Properties

Explore how to use Reflect methods to dynamically get, set, and inspect properties of JavaScript objects. Understand how Reflect integrates with Proxy for advanced metaprogramming and how it supports method invocation and property iteration.

Getting and setting properties

In Dynamic Access, we explored ways to dynamically access properties. Reflect provides alternatives to both get and set properties.

Example

Let’s take a look at the Person class:

Node.js
'use strict';
//START:PROPERTIES
class Person {
constructor(age) {
this.age = age;
}
play() { console.log(`The ${this.age} year old is playing`); }
get years() { return this.age; }
}
//END:PROPERTIES

For example, to access the age property on an instance of sam of Person, we can perform sam.age.

Reflect's get and set

If we don’t know the name of the property at code writing time, we can pass the property name as a string to Reflect’s get() ...