JavaScript - Reflect.apply() 方法
JavaScript ES6 标准包含 Reflect.apply() 方法,该方法使用给定的 this 值和参数调用一个函数。此方法与 Function.prototype.apply() 方法类似,但它提供了一种更灵活、更可预测的函数应用方式。
Reflect.apply() 是一个静态方法,即使函数缺少原型属性也可以使用,这使得它比 Function.prototype.apply() 更佳。此外,Function.prototype.apply() 仅限于函数,而 Reflect.apply() 兼容内置方法和函数。
语法
以下是 JavaScript Reflect.apply() 方法的语法 -
Reflect.apply(target, thisArgument, argumentList)
参数
此方法接受三个参数。下文将分别介绍 -
target - 调用目标函数。
thisArgument - 包含调用目标函数所需的 this 值。
argumentsList - 类似数组的对象,用于指定调用目标函数所需的参数。
返回值
此方法返回使用指定的 this 值和参数调用给定目标函数的结果。
示例
示例 1
让我们看下面的示例,我们将使用 Reflect.apply() 调用 add() 函数,参数分别为 11 和 4。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function add(x, y) {
return x + y;
}
const a = Reflect.apply(add, null, [11, 4]);
document.write(a);
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示一个数字。
示例 2
考虑另一种场景,我们将使用 Reflect.apply() 调用对象上的 greet() 方法。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
y: 'TutorialsPoint',
greet() {
return `Hello, Welcome To ${this.y}`;
}
};
const a = Reflect.apply(x.greet, x, []);
document.write(a);
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将使用 Reflect.apply() 调用 Math.max() 函数,并以数字数组作为参数。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = [11, 12, 3, 22, 4];
const a = Reflect.apply(Math.max, null, x);
document.write(a);
</script>
</body>
</html>
当我们执行上述脚本时,会弹出输出窗口,显示网页上的文本。

