How To Use Apply Function In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 09-10-2020

In Java Script we can use apply() method it will write a method that can be used on different objects. so today we discuss how to use apply method

How To Use Apply Function In JavaScript With Example

The JavaScript apply() Method

The apply() method is similar to the call() method (previous chapter).

In this example the fullName method of person is applied on person1:

<script>
    var person = {
        fullName: function() {
            return this.firstName + " " + this.lastName;
        }
    }
    var person1 = {
        firstName:"John",
        lastName: "Doe"
    }
    var x = person.fullName.apply(person1);
    document.getElementById("demo").innerHTML = x;
</script>


Complete Code For Using Apply Function In JavaScript 

<!DOCTYPE html>
<html>
<head>
    <title>How To Use Apply Function In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How To Use Apply Function In JavaScript</h1>
    </div>

    <div class="well">
        <h2 id="demo"></h2>

        <script>
            var person = {
                fullName: function() {
                    return this.firstName + " " + this.lastName;
                }
            }
            var person1 = {
                firstName:"John",
                lastName: "Doe"
            }
            var x = person.fullName.apply(person1);
            document.getElementById("demo").innerHTML = x;
        </script>
    </div>
</div>
</body>
</html>

 

Related Post