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 object
1const user = { name: "Alice", age: 25 };
// Define handler with traps
2const handler = {
// Get trap intercepts property access
3 get(target, prop) {
// Log when property is accessed
4 console.log(`Getting ${prop}`);
// Return the actual property value
5 return target[prop];
6 },
// Set trap intercepts property assignment
7 set(target, prop, value) {
// Log when property is set
8 console.log(`Setting ${prop} to ${value}`);
// Actually set the property
9 target[prop] = value;
// Return true to indicate success
10 return true;
11 }
12};
// Create proxy with handler
13const proxy = new Proxy(user, handler);
// Triggers the get trap (prints "Getting name"), then prints Alice
14console.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

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

More JavaScript examples at level 5

← JavaScript typing practice