JavaScript Handler apply() 方法
在 JavaScript 中,handler.apply() 方法允许您使用特定参数和上下文调用函数(类似于函数调用的陷阱)。它用于调用函数,但除了 this 值之外,还允许指定一个参数数组。这在您希望使用特定对象作为上下文调用函数,或者您希望将一个参数数组传递给函数的情况下尤其有用。此方法类似于 call() 方法,但我们不是传递单个参数,而是传递一个参数数组。
语法
以下是 JavaScript handler.apply() 方法的语法 -
new Proxy(target, {
apply(target, thisArg,argumentsList) {}
});
参数
- target − 保存目标对象。
- thisArg − 调用的 this 参数。
- argumentsList − 包含调用的参数列表。
返回值
此方法可以返回任何值。
示例 1
让我们看下面的示例,我们将使用包含要传递给 add 函数的参数的数组,然后使用 apply() 调用该函数。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function add(a, b) {
return a + b;
}
const x = [22, 11];
const y = add.apply(null, x);
document.write(y);
</script>
</body>
</html>
示例 2
考虑另一种场景,我们将在不同的上下文中调用一个函数。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
car: 'Audi Q6',
greet: function() {
return 'Ford ' + this.car;
}
};
const y = {
car: 'Mustang'
};
const a = x.greet.apply(y);
document.write(a);
</script>
</body>
</html>
示例 3
在下面的示例中,我们将把数组的所有元素作为单独的参数传递给函数。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function sum() {
const x = Array.from(arguments);
return x.reduce((acc, val) => acc + val, 0);
}
const y = [10, 20, 30, 40, 50];
const result = sum.apply(null, y);
document.write(result);
</script>
</body>
</html>
执行上述脚本后,输出窗口将会弹出,并在网页上显示总和。
示例 4
以下示例将通过调用 Math.max 函数并以数组作为参数来查找数组中的最大值。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = [11, 222, 3, 412];
const result = Math.max.apply(null, x);
document.write(result);
</script>
</body>
</html>
执行上述脚本后,将弹出输出窗口,显示网页上数组中的最大数字。

