Sub topic 8
Proxying Functions with apply and construct
Earlier chapters used proxies on plain objects. Functions are objects too, and they have two extra internal methods. [[Call]] runs when you call a function, and [[Construct]] runs when you use new. A proxy around a function can intercept both, through the apply and construct traps.
This chapter assumes you know how this is bound in regular calls, method calls, call/apply, and new. It also assumes you know how classes and extends work, and that you have read the earlier chapters on traps and Reflect.
Which Proxies Can Be Called or Constructed
When a proxy is created, it copies only the capabilities its target has:
- If the target has
[[Call]], meaning it is any kind of function, the proxy is callable andtypeof proxyis'function'. - If the target has
[[Construct]], the proxy can be used withnew. Regular functions and classes have it. Arrow functions, methods defined with shorthand syntax, and most built-in methods do not.
The handler cannot add these capabilities. An apply trap on a proxy around a plain object never runs, and a construct trap on a proxy around an arrow function never runs either.
const arrow = () => {};
const proxy = new Proxy(arrow, {
construct() {
console.log('never logged');
return {};
}
});
try {
new proxy();
} catch (err) {
console.log(err instanceof TypeError); // true: proxy is not a constructor
}
const notCallable = new Proxy({}, {
apply() {
return 'never returned';
}
});
try {
notCallable();
} catch (err) {
console.log(err instanceof TypeError); // true: notCallable is not a function
}The Trap Signatures
| Operation on the proxy | Trap | Trap arguments | Default via Reflect |
|---|---|---|---|
| `proxy(...args)`, `obj.method(...args)`, `proxy.call(t, ...args)`, `proxy.apply(t, args)` | `apply` | `target, thisArg, argumentsList` | `Reflect.apply(target, thisArg, argumentsList)` |
| `new proxy(...args)`, `super(...args)` in a subclass, `Reflect.construct(proxy, args, nt)` | `construct` | `target, argumentsList, newTarget` | `Reflect.construct(target, argumentsList, newTarget)` |
argumentsList is always a real array, even when the call passed no arguments. thisArg is whatever this the caller supplied: undefined for a plain call, the object for a method call, or the first argument to call/apply. The proxy does not apply the sloppy-mode rule that turns undefined into the global object. The target function does that itself when Reflect.apply invokes it.
Intercepting Calls with apply
The trap gets everything needed to repeat the call exactly. Forwarding with Reflect.apply keeps the original this and arguments.
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
const traced = new Proxy(greet, {
apply(target, thisArg, args) {
const who = thisArg === undefined ? 'undefined' : thisArg.name;
console.log(`call ${target.name} this=${who} args=${JSON.stringify(args)}`);
return Reflect.apply(target, thisArg, args);
}
});
const user = { name: 'Ada', greet: traced };
console.log(user.greet('Hi'));
// call greet this=Ada args=["Hi"]
// Hi, Ada
console.log(traced.call({ name: 'Grace' }, 'Hello'));
// call greet this=Grace args=["Hello"]
// Hello, Grace
console.log(Reflect.apply(traced, { name: 'Linus' }, ['Hey']));
// call greet this=Linus args=["Hey"]
// Hey, Linustraced.call(...) still reaches the trap. The expression traced.call reads call through the proxy's get path, finds Function.prototype.call, and runs it with this set to the proxy. call then invokes the proxy's [[Call]], which runs the trap. The same is true of apply and of bind: a bound copy of the proxy calls the proxy, which calls the trap.
Properties such as name and length need no trap. They are ordinary property reads, so with no get trap they fall through to the target. traced.name is 'greet'.
Changing arguments and results
The trap can change what goes in and what comes out. This wrapper rejects non-numeric arguments and rounds the result:
function divide(a, b) {
return a / b;
}
const safeDivide = new Proxy(divide, {
apply(target, thisArg, args) {
if (args.length !== target.length || !args.every(Number.isFinite)) {
throw new TypeError(`${target.name} expects ${target.length} finite numbers`);
}
if (args[1] === 0) {
throw new RangeError('division by zero');
}
const result = Reflect.apply(target, thisArg, args);
return Math.round(result * 100) / 100;
}
});
console.log(safeDivide(10, 3)); // 3.33
// safeDivide(10, '3'); // TypeError
// safeDivide(1, 0); // RangeErrorMemoizing a pure function
The trap can also skip the target completely. Here a cache answers repeated calls:
function memoize(fn) {
const cache = new Map();
return new Proxy(fn, {
apply(target, thisArg, args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = Reflect.apply(target, thisArg, args);
cache.set(key, result);
return result;
}
});
}
let calls = 0;
const slowSquare = memoize((n) => {
calls++;
return n * n;
});
slowSquare(4);
slowSquare(4);
console.log(calls); // 1The arrow function works as a target here because only [[Call]] is needed. Using JSON.stringify as the key is only safe for arguments that serialize uniquely. Objects with the same JSON but different identity would collide.
Timing sync and async calls
A timing trap has to handle the three ways a call can end: it returns a value, it throws, or it returns a promise that settles later.
function timed(fn, log = console.log) {
return new Proxy(fn, {
apply(target, thisArg, args) {
const start = performance.now();
const report = () =>
log(`${target.name} took ${(performance.now() - start).toFixed(1)}ms`);
let result;
try {
result = Reflect.apply(target, thisArg, args);
} catch (err) {
report();
throw err;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
return result.finally(report);
}
report();
return result;
}
});
}
const wait = timed(function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms, 'done'));
});
wait(50).then(console.log); // "wait took 50.xms", then "done"finally returns a new promise. It resolves to the same value as the original or rejects with the same reason, so callers see the result unchanged.
Intercepting new with construct
The construct trap runs for new proxy(...). Its third argument, newTarget, is the constructor that new was applied to. For new proxy() that is the proxy itself. newTarget decides which prototype the new instance gets and what new.target is inside the constructor.
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(p instanceof CountedPoint); // true
console.log(created); // 1Here newTarget is CountedPoint. Reflect.construct reads CountedPoint.prototype, which the proxy forwards to Point.prototype. That is why both instanceof checks pass.
The trap must return an object. If it returns a primitive, new throws a TypeError. This is one of the proxy invariants covered in a later chapter. Returning a different object from the one the target would build is allowed, which makes construct a natural place to hand out cached instances or singletons.
Why newTarget matters: subclassing a proxied class
newTarget matters most when another class extends the proxy. In that case super() inside the subclass calls the proxy's [[Construct]] with newTarget set to the subclass.
class Base {
constructor() {
this.kind = new.target.name;
}
}
const Tracked = new Proxy(Base, {
construct(target, args, newTarget) {
console.log(`construct ${newTarget.name}`);
return Reflect.construct(target, args, newTarget);
}
});
class Child extends Tracked {
hello() {
return 'hello from Child';
}
}
const c = new Child(); // logs "construct Child"
console.log(c.kind); // 'Child'
console.log(c.hello()); // 'hello from Child'
console.log(c instanceof Child); // trueNow see what happens if the trap drops newTarget:
const Broken = new Proxy(Base, {
construct(target, args) {
return new target(...args); // same as Reflect.construct(target, args)
}
});
class BrokenChild extends Broken {
hello() {
return 'hi';
}
}
const b = new BrokenChild();
console.log(b.kind); // 'Base'
console.log(b instanceof BrokenChild); // false
console.log(typeof b.hello); // 'undefined'The instance was built with Base.prototype, so the subclass's methods are missing. newTarget plays the same role for construct that the receiver plays for get and set: if you leave it out, inheritance breaks without any error.
Bridging Calls and Construction
The two traps can convert one operation into the other. A class throws when called without new, but a class still has [[Call]]; its call behavior just throws. So the proxy is callable, the apply trap runs, and it can construct the class instead:
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const vec = new Proxy(Vec, {
apply(target, thisArg, args) {
return Reflect.construct(target, args);
}
});
const v1 = vec(1, 2); // no new needed
const v2 = new vec(3, 4); // still works: no construct trap, so default behavior
console.log(v1 instanceof Vec, v2 instanceof Vec); // true trueHere Reflect.construct uses target as the new target by default. That is correct because nothing is subclassing in a plain call.
Edge Cases to Remember
- Identity.
traced !== greet. If you register the proxy as an event listener, you must remove the proxy, not the original function. AWeakMapfrom original to proxy lets you reuse one wrapper per function. - Method calls on objects. An
applytrap only fires for the function it wraps. To trace every method of an object, agettrap must return function proxies. The patterns chapter builds that. Function.prototype.toString. Calling it on a function proxy does not return the target's source. Engines return a native-code placeholder such asfunction () { [native code] }. Code that inspects function source will see the difference.thisinside the trap. Inside a trap,thisis the handler object, not the proxy orthisArg. Use the trap's parameters.- Throwing from the trap. The exception goes straight to the caller, as if the function had thrown. The target never runs.
Exercise
You wrap an arrow function with new Proxy(arrowFn, { construct(t, args) { return { made: true }; } }) and call new proxy(). What happens, and why?
Show answer
It throws a TypeError ("not a constructor") and the trap never runs. A proxy gets [[Construct]] only if its target has one, and arrow functions do not. To make the proxy constructible, use a regular function or a class as the target.
Exercise
A construct trap on a proxied class Model is written as construct(target, args) { return Reflect.construct(target, args); }. Then class User extends ModelProxy { save() {} } is defined, and new User().save() throws "save is not a function". Explain the cause and fix the trap.
Show answer
Without the third argument, Reflect.construct uses target (Model) as the new target, so the instance's prototype is Model.prototype instead of User.prototype, and new.target inside Model is Model. The fix is to forward newTarget: construct(target, args, newTarget) { return Reflect.construct(target, args, newTarget); }.
Exercise
Write an apply trap that counts how many times a function is called and passes through this, the arguments, and the return value unchanged. Then explain why counted.call(obj, 1) is also counted.
Show answer
let n = 0; const counted = new Proxy(fn, { apply(target, thisArg, args) { n++; return Reflect.apply(target, thisArg, args); } });. counted.call reads Function.prototype.call through the proxy, and call invokes the proxy's [[Call]] with obj as this. That runs the apply trap, so the count goes up and thisArg is obj.