/    /  Javascript-Apply

Javascript-Apply

 

The apply() method is provided to write methods, which can be used on various objects. It is different from the javascript function call() because it takes arguments as an array.

 

Syntax:

 

apply()

 

Return Value:

 

Returns the method values of a given function.

 

Example:

 

illustrates the apply() function without arguments.

 

<!DOCTYPE html>
<html>

<head>
      <title>
              JavaScript apply() Method
              without argument
      </title>
</head>

<body>
       <h1>I2TUTORIALS</h1>

       <h2>
           JavaScript apply() Method
       </h2>

       <h4>
           It displays the details of second student
       </h4>

       <p id="GFG"></p>

       <!-- Script to use apply() method -->
       <script>
               var student = {
                      details: function() {
                               return this.name + "<br>" + this.class;
                      }
               }
               var stud1 = {
                      name:"student1",
                      class: "11th",
               }
               var stud2 = {
                      name:"student2",
                      class: "11th",
               }
                        
               var x = student.details.apply(stud2);
               document.getElementById("GFG").innerHTML = x;
      </script>
</body>

</html>

 

OUTPUT:

 

I2TUTORIALS

JavaScript apply() Method

It displays the details of second student

student2

11th

 

Example :

 

illustrates the apply() function with arguments.

 

<!DOCTYPE html>
<html>

<head>
       <title>
               JavaScript apply() Method
               with argument
       </title>
</head>

<body>
       <h1>I2TUTORIALS</h1>

       <h2>
           JavaScript apply() Method
       </h2>

       <h4>
           It displays the details of second student
       </h4>

       <p id="GFG"></p>
       <!-- Script to use apply() method -->
       <script>
               var student = {
                      details: function(section, rollnum) {
                              return this.name + "<br>" + this.class
                                      + " " + section + "<br>" + rollnum;
                      }
               }
               var stud1 = {
                      name:"student1",
                      class: "11th",
               }
               var stud2 = {
                      name:"student2",
                      class: "11th",
               }

               var x = student.details.apply(stud2, ["A", "56"]);
               document.getElementById("GFG").innerHTML = x;
      </script>
</body>

</html>

 

OUTPUT:

 

I2TUTORIALS

JavaScript apply() Method

It displays the details of second student

student2

11th A

56