Blog>
Snippets

Changing 'this' with 'call' and 'apply'

Provide examples on how to use 'call' and 'apply' to invoke a function with a specified 'this' value and arguments.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call and Apply Example</title>
    <style>
        /* Simple CSS to style the button */
        button {
            margin: 10px;
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <button id="callBtn">Call Example</button>
    <button id="applyBtn">Apply Example</button>

    <script>
        // Function that uses 'this' keyword
        function introduce(language1, language2) {
            alert(`Hello, I am ${this.name} and I know ${language1} and ${language2}.`);
        }

        // Object that we will use as 'this'
        const person = {name: 'Alice'};

        // Grabbing our buttons
        const callBtn = document.getElementById('callBtn');
        const applyBtn = document.getElementById('applyBtn');

        // 'Call' is used to run the function with a specified 'this'
        // And pass arguments individually
        callBtn.addEventListener('click', function() {
            introduce.call(person, 'JavaScript', 'Python');
        });

        // 'Apply' is used to run the function with a specified 'this'
        // And pass all arguments as an array
        applyBtn.addEventListener('click', function() {
            introduce.apply(person, ['JavaScript', 'Python']);
        });
    </script>
</body>
</html>
This HTML contains two buttons and JavaScript code demonstrating the usage of 'call' and 'apply' methods. The 'introduce' function is invoked with 'call', which takes individual arguments after the context (person object), and with 'apply', which takes an array of arguments. Clicking each button will run 'introduce' function with 'person' as 'this' and showing an alert with the introduction.