Reflect.apply()
Базовый уровень Широко доступно
Эта функция хорошо зарекомендовала себя и работает на многих устройствах и в различных версиях браузеров. Она доступна во всех браузерах с сентября 2016 года.
Статический метод 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 - Значение
this, предоставленное для вызоваtarget. -
argumentsList - Объект, похожий на массив, указывающий аргументы, с которыми должен быть вызван
target.
Возвращаемое значение
Результат вызова данной функции target с указанным значением this и аргументами.
Исключения
-
TypeError - Выбрасывается, если
targetне является функцией илиargumentsListне является объектом.
Описание
Reflect.apply() обеспечивает рефлексивную семантику вызова функции. То есть, Reflect.apply(target, thisArgument, argumentsList) семантически эквивалентен:
Math.floor.apply(null, [1.75]); Reflect.apply(Math.floor, null, [1.75]);
Единственные различия:
-
Reflect.apply()принимает функцию для вызова в качестве параметраtarget, а не в контекстеthis. -
Reflect.apply()выбрасывает исключение, еслиargumentsListопущен, вместо того чтобы по умолчанию вызывать функцию без параметров.
Reflect.apply() вызывает внутренний метод объекта [[Call]] для target.
Примеры
Использование Reflect.apply()
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"
Спецификации
Совместимость с браузерами
| Десктопные | Мобильные | Серверные | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on iOS | Samsung Internet | WebView Android | WebView on iOS | Bun | Deno | Node.js | |
apply |
49 |
12 |
42 |
36 |
10 |
49 |
42 |
36 |
10 |
5.0 |
49 |
10 |
1.0.0 |
1.0 |
6.0.0 |
Смотрите также
- Полифил
Reflect.applyвcore-js - es-shims полифил
Reflect.apply ReflectFunction.prototype.apply()handler.apply()
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/apply