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.
Code
// 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: devexCode 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `formatMetric` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.