JavaScript ES6 标准包括 Reflect.apply() 方法,该方法调用具有给定 'this' 值和参数的函数。此方法类似于 Function.prototype.apply() 方法,但它提供了一种更灵活和可预测的方法来应用函数。
Reflect.apply() 是一种静态方法,即使在函数缺少 prototype 属性的情况下也可以使用,这使得它成为比 Function.prototype.apply() 更好的选择。此外,虽然 Function.prototype.apply() 仅限于函数,但 Reflect.apply() 与内置方法和函数兼容。
语法
以下是 JavaScript Reflect.apply() 方法的语法 -
Reflect.apply(target, thisArgument, argumentsList)
参数
此方法接受三个参数。相同的描述如下 -
- target − 它是对 target 函数的调用。
- thisArgument − 它包含调用目标函数所需的 'this' 值。
- argumentsList − 它是一个类似对象的数组,指定了应该用来调用目标的参数。
返回值
此方法返回使用指定的 'this' 值和参数调用给定目标函数的结果。
示例 1
让我们看看下面的示例,我们将使用 Reflect.apply() 调用参数为 11 和 4 的 add() 函数。
<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: 'qikepu.com',
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>
当我们执行上述脚本时,会弹出输出窗口,在网页上显示文本。