Creating Computed Properties with Proxies
Use a Proxy to create computed properties that calculate their value dynamically when accessed.
const personData = {
firstName: 'John',
lastName: 'Doe',
birthYear: 1990
};
// Define a getter and setters for a computed property
const computedFullName = {
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(fullName) {
const parts = fullName.split(' ');
this.firstName = parts[0];
this.lastName = parts[1] || '';
}
};
// Create a proxy to handle the computed properties
const personProxy = new Proxy(personData, {
get(target, property) {
if (property in computedFullName) {
return Reflect.apply(computedFullName[property], target, []);
}
return target[property];
},
set(target, property, value) {
if (property in computedFullName) {
Reflect.apply(computedFullName[property], target, [value]);
} else {
target[property] = value;
}
return true;
}
});
A Proxy is created for the 'personData' object to handle computed properties. A separate 'computedFullName' object defines getters and setters for the 'fullName' computed property, which concatenates 'firstName' and 'lastName' or splits the full name into its components. The proxy's 'get' and 'set' traps delegate to these getters and setters or directly access the target properties.
console.log(personProxy.fullName); // 'John Doe'
personProxy.fullName = 'Jane Smith';
console.log(personProxy.firstName); // 'Jane'
console.log(personProxy.lastName); // 'Smith'
This code demonstrates accessing and setting the computed property 'fullName' on the 'personProxy' object. The Proxy's 'get' and 'set' handlers are invoked, calculating the full name or updating the individual first and last names respectively.