Reflect.apply()

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

Reflect.apply() 静态方法会根据指定的方式调用目标函数。

试一试

console.log(Reflect.apply(Math.floor, undefined, [1.75]));
// Expected output: 1

console.log(
  Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]),
);
// Expected output: "hello"

console.log(
  Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index,
);
// Expected output: 4

console.log(Reflect.apply("".charAt, "ponies", [3]));
// Expected output: "i"

语法

js
Reflect.apply(target, thisArgument, argumentsList)

参数

目标

要调用的目标函数。

thisArgument

调用 target 时提供的 this 值。

argumentsList

一个 类数组对象,指定了调用 target 时使用的参数。

返回值

使用指定的 this 值和参数调用给定的 target 函数的结果。

异常

TypeError

如果 target 不是函数或 argumentsList 不是对象,则抛出此错误。

描述

Reflect.apply() 提供了函数调用的反射语义。也就是说,Reflect.apply(target, thisArgument, argumentsList) 在语义上等同于

js
Math.floor.apply(null, [1.75]);
Reflect.apply(Math.floor, null, [1.75]);

唯一的区别是

  • Reflect.apply() 将要调用的函数作为 target 参数,而不是 this 上下文。
  • 如果省略 argumentsListReflect.apply() 会抛出错误,而不是默认使用无参数调用。

Reflect.apply() 调用 target[[Call]] 对象内部方法

示例

使用 Reflect.apply()

js
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;

Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"

Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4

Reflect.apply("".charAt, "ponies", [3]);
// "i"

规范

规范
ECMAScript® 2026 语言规范
# sec-reflect.apply

浏览器兼容性

另见