← 中文资源

简体中文版本

Reflect.apply 安全转发接收者与参数元组

使用 Reflect.apply(fn, thisArg, args) 安全调用函数,既不惧对象自身遮蔽 .apply 属性,也省去 Function.prototype.apply.call 的冗长写法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

活动部件是函数 formatMetric。

使用要点

  • 语言裸安装一份就能原样运行。
  • 跑完文件,输出里会留下标记——safe dispatch:、max score:、sliced:。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件在加载时定义 formatMetric。

主要签名是 function formatMetric(unit, precision)

核心语句

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

代码示例

// 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));