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])); // 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" 構文
Reflect.apply(target, thisArgument, argumentsList)
引数
target-
呼び出し対象の関数。
thisArgument-
targetの呼び出す際のthis値を提供する。 argumentsList-
targetと一緒に呼び出す引数を指定する配列風オブジェクト。
返値
指定された target 値と引数の条件で対象の関数を呼び出したときの結果です。
例外
TypeError: target が呼び出せない場合。
解説
ES5 では、ふつう Function.prototype.apply() メソッドを使用することで、指定された this の値と arguments で配列 (または 配列風オブジェクト) により引数を指定することで、関数を呼び出すことができます。
js
Function.prototype.apply.call(Math.floor, undefined, [1.75]); Reflect.apply() を使うと、それほど冗長ではなく理解しやすくなります。
例
>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> |