Proxy Object Handler in JavaScript
Level 5326 keystrokes
Proxy allows you to intercept and customize operations on objects like getting and setting properties.
JavaScript code
// Create a simple user object1const user = { name: "Alice", age: 25 };// Define handler with traps2const handler = { // Get trap intercepts property access3 get(target, prop) { // Log when property is accessed4 console.log(`Getting ${prop}`); // Return the actual property value5 return target[prop];6 }, // Set trap intercepts property assignment7 set(target, prop, value) { // Log when property is set8 console.log(`Setting ${prop} to ${value}`); // Actually set the property9 target[prop] = value; // Return true to indicate success10 return true;11 }12};// Create proxy with handler13const proxy = new Proxy(user, handler);// Triggers the get trap (prints "Getting name"), then prints Alice14console.log(proxy.name);// Triggers the set trap (prints "Setting age to 30")15proxy.age = 30;Output
Getting name Alice Setting age to 30
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
;× 10{× 7}× 7,× 6(× 6)× 6.× 5=× 5`× 4$× 3