JavaScript - Reflect.apply() 方法



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** - 它是對目標函式的呼叫。

  • **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>

當我們執行上述指令碼時,輸出視窗將彈出,在網頁上顯示文字。

廣告