Sub topic 8
Proxying Functions with apply and construct
This chapter assumes you know how this is bound in function calls, how new creates objects from constructors and classes, and how get traps and Reflect forwarding work from earlier chapters.
Functions are objects, so you can wrap them in a proxy like any other object. They also have two internal methods that plain objects lack. [[Call]] runs when you call the function, and [[Construct]] runs when you use it with new. The apply and construct traps intercept these two methods.
Which trap fires for which operation
| Trap | Internal method | Triggered by | Default forwarding |
|---|---|---|---|
| `apply(target, thisArg, args)` | `[[Call]]` | `f()`, `obj.f()`, `f.call()`, `f.apply()`, `Reflect.apply()` | `Reflect.apply(target, thisArg, args)` |
| `construct(target, args, newTarget)` | `[[Construct]]` | `new f()`, `Reflect.construct()`, `super()` from a subclass | `Reflect.construct(target, args, newTarget)` |
Note that args is always a real array, not an arguments object.
Tracing calls with apply
function sum(a, b) {
return a + b;
}
const traced = new Proxy(sum, {
apply(target, thisArg, args) {
console.log(`called with ${args.join(', ')}`);
return Reflect.apply(target, thisArg, args);
}
});
console.log(traced(1, 2)); // logs "called with 1, 2", then 3thisArg is whatever this would have been for the call. For a method call it is the object to the left of the dot. You must forward it, or methods lose their object:
const counter = {
count: 0,
increment: new Proxy(function () {
return ++this.count;
}, {
apply(target, thisArg, args) {
console.log('thisArg is counter:', thisArg === counter);
return Reflect.apply(target, thisArg, args);
}
})
};
console.log(counter.increment()); // logs "thisArg is counter: true", then 1Because the trap controls the return value, apply can also change behavior: it can cache results, check argument types, or measure how long a call takes.
Intercepting new with construct
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let created = 0;
const CountedPoint = new Proxy(Point, {
construct(target, args, newTarget) {
created++;
return Reflect.construct(target, args, newTarget);
}
});
const p = new CountedPoint(1, 2);
console.log(p.x, p.y); // 1 2
console.log(p instanceof Point); // true
console.log(created); // 1newTarget is the constructor that new was originally applied to. Here that is the proxy itself. Reflect.construct reads newTarget.prototype to choose the new object's prototype. The read goes through the proxy to Point.prototype, so instanceof still works. If a subclass extends the proxy, newTarget is the subclass. Forwarding it keeps the subclass's prototype on the result, so always pass newTarget through rather than dropping it.
Common errors
- Returning a primitive from
construct. The trap must return an object.return 42throws a TypeError. This is one of the proxy invariants covered in a later chapter. - Calling
target(...args)directly. This dropsthisArg. UseReflect.applyinstead. - Using
new target(...args)inconstruct. This ignoresnewTargetand breaks subclassing. UseReflect.construct. - Using an
applytrap to blocknew. Calling and constructing are separate operations. To forbidnew, add aconstructtrap that throws.
Exercise
You wrap const double = (n) => n * 2 in a proxy that has both an apply and a construct trap. What happens with proxy(4) and with new proxy(4), and why?
Show answer
proxy(4) runs the apply trap and, if it forwards with Reflect.apply, returns 8. new proxy(4) throws a TypeError without running the construct trap, because arrow functions have no [[Construct]] internal method and a proxy is constructible only when its target is.
Exercise
Write a construct trap that throws if any argument is undefined and otherwise creates the instance normally.
Show answer
construct(target, args, newTarget) { if (args.some((a) => a === undefined)) { throw new TypeError('missing argument'); } return Reflect.construct(target, args, newTarget); }