Sub topic 1
What Happens When You Touch an Object: Internal Methods
Prerequisites
This chapter assumes you know JavaScript objects and property descriptors, prototype-chain lookup, how this binds, ES6 syntax, and basic Symbols.
Internal Methods
Every object operation runs through an internal method that the specification defines. Reading obj.x calls [[Get]]. Assigning obj.x = 1 calls [[Set]]. The in operator calls [[HasProperty]], and delete calls [[Delete]]. Your code cannot call these methods directly. A Proxy lets you replace them.
Your First Proxy: Target and Handler
new Proxy(target, handler) takes two arguments:
- The target is the object being wrapped. Any operation you don't intercept goes straight to it.
- The handler is an object whose methods, called traps, replace specific internal methods.
const target = { greeting: 'hello' };
const handler = {
get(target, prop, receiver) {
console.log(`get ${String(prop)}`);
return Reflect.get(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.greeting); // logs "get greeting", then "hello"Reflect.get performs the default read, so the trap adds logging and changes nothing else.
Traps: The Operations a Proxy Can Intercept
Each trap corresponds to one internal method:
| Trap | Internal method | Triggered by |
|---|---|---|
| `get` | `[[Get]]` | `obj.x`, `obj[key]` |
| `set` | `[[Set]]` | `obj.x = v` |
| `has` | `[[HasProperty]]` | `key in obj` |
| `deleteProperty` | `[[Delete]]` | `delete obj.x` |
| `ownKeys` | `[[OwnPropertyKeys]]` | `Object.keys`, `Reflect.ownKeys` |
| `apply` | `[[Call]]` | `fn()` |
| `construct` | `[[Construct]]` | `new Fn()` |
The spec defines 13 traps in total. If you leave a trap out, the proxy forwards that operation to the target unchanged.
Intercepting Reads and Writes with get and set
The set trap receives (target, prop, value, receiver) and must return a boolean. A common mistake is to forget the return value. In strict mode, returning false makes the assignment throw a TypeError.
const person = new Proxy({}, {
set(target, prop, value, receiver) {
if (prop === 'age' && (!Number.isInteger(value) || value < 0)) {
throw new TypeError('age must be a non-negative integer');
}
return Reflect.set(target, prop, value, receiver);
}
});
person.age = 30; // stored
try {
person.age = -1;
} catch (err) {
console.log(err.message); // "age must be a non-negative integer"
}
console.log(person.age); // 30Exercise
Write a proxy whose get trap returns 0 for any property the target does not have, and otherwise returns the real value.
Show answer
const counts = new Proxy({}, { get(target, prop, receiver) { return prop in target ? Reflect.get(target, prop, receiver) : 0; } }); console.log(counts.apples); // 0