Reflect.apply()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年9月.
Reflect.apply() は静的メソッドで、指定された引数とともに対象となる関数を呼び出します。
試してみましょう
console.log(Reflect.apply(Math.floor, undefined, [1.75]));
// 予想される結果: 1
console.log(
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]),
);
// 予想される結果: "hello"
console.log(
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index,
);
// 予想される結果: 4
console.log(Reflect.apply("".charAt, "ponies", [3]));
// 予想される結果: "i"
構文
js
Reflect.apply(target, thisArgument, argumentsList)
引数
target-
呼び出し対象の関数。
thisArgument-
targetの呼び出す際のthis値を提供する。 argumentsList-
targetを呼び出す際の引数を指定する配列風オブジェクト。
返値
指定された 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()は、thisコンテキストの代わりに、呼び出す関数をtarget引数として取ります。Reflect.apply()は、argumentsListが省略された場合にデフォルトで引数なしの呼び出しを行わず、例外が発生します。
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"
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-reflect.apply> |