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

瀏覽器相容性

另見