• JavaScript Video Tutorials

JavaScript - Reflect.apply() Method



The JavaScript ES6 standard includes the Reflect.apply() method, which calls a function with a given 'this' value and arguments. This method is similar to the Function.prototype.apply() method, but it provides a more flexible and predictable way to apply a function.

Reflect.apply() is a static method that may be used even in cases when the function lacks a prototype property, which makes it a better option than Function.prototype.apply(). Furthermore, while Function.prototype.apply() is limited to functions, Reflect.apply() is compatible with built-in methods and functions.

Syntax

Following is the syntax of JavaScript Reflect.apply() method −

Reflect.apply(target, thisArgument, argumentsList)

Parameters

This method accepts three parameters. The same are described below −

  • target − It is a call to the target function.

  • thisArgument − It contains 'this' value which is required for calling the target function.

  • argumentsList − It is a array like object specifying the arguments with which the target should be called.

Return value

This method returns the result of calling the given target function with the specified 'this' value and arguments.

Examples

Example 1

Let's look at the following example, where we are going to use the Reflect.apply() to call the add() function with arguments 11 and 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>

If we execute the above program, it will displays a number on the webpage.

Example 2

Consider another scenario where we are going to use to Reflect.apply() to call the greet() method on the object.

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

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to use the Reflect.apply() to call the Math.max() function with array of numbers as arguments.

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

When we execute the above script, the output window will pop up, displaying the text on the webpage.

Advertisements