Reflect.apply Dispatches Safely With Tuples

Invoke functions with an explicit this receiver and argument array via Reflect.apply, avoiding collisions when objects shadow .apply or lack Function methods.

JavascriptSecurity Boundaries

Code

snippet
// Safe even if a custom callable shadows `.apply` with a non-function property
function formatMetric(unit, precision) {
  return `${this.value.toFixed(precision)} ${unit}`;
}
formatMetric.apply = 'corrupted-property';

const reading = { value: 42.195 };
console.log('safe dispatch:', Reflect.apply(formatMetric, reading, ['km', 2]));

// Works cleanly with built-ins and null receivers without spreading at call sites
const scores = [14, 88, 53, 91, 67];
console.log('max score:', Reflect.apply(Math.max, null, scores));

// Calling String.prototype.slice on an arbitrary string with tuple args
const span = [0, 5];
console.log('sliced:', Reflect.apply(String.prototype.slice, 'devexamples', span));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

safe dispatch: 42.20 km
max score: 91
sliced: devex

Code mechanics — Reflect.apply Dispatches Safely With Tuples

Everything happens inside the function formatMetric.

Watch out for

  • No package installation, no environment variables, no setup steps.

Using it

Central invocation contract reads function formatMetric(unit, precision)

The demo output is labeled (safe dispatch:, max score:, sliced:); each label names the call that printed it.

Key statements

return `${this.value.toFixed(precision)} ${unit}`;

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `formatMetric` at load time.