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>

执行上述脚本后,输出窗口将弹出,在网页上显示数组中的最大数字。

广告
© . All rights reserved.