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>

執行上述指令碼後,輸出視窗將彈出,在網頁上顯示陣列中的最大數字。

廣告