JavaScript - call() method

revision:


Category: function.prototype

The call() method invokes/calls a function with a specified context : a given "this" value and arguments provided individually. In other words, a function can be tied into an object as if it belonged to the object. call() can also be used with functions that accept multiple arguments.

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call(), an object can use a method belonging to another object.

Syntax :

            call(thisArg)
            call(thisArg, arg1)
            call(thisArg, arg1, /* …, */ argN)
   

Parameters

thisArg : the value to use as "this" when calling "func". If the function is not in strict mode, "null" and "undefined" will be replaced with the global object, and primitive values will be converted to objects.

arg1, …, argN : optional. Arguments for the function.

Examples

            function greet() {
                console.log(this.animal, "typically sleep between", this.sleepDuration);
            }
            const obj = {
                animal: "cats",
                sleepDuration: "12 and 16 hours",
            };
            greet.call(obj); // cats typically sleep between 12 and 16 hours
    

Practical examples

example: call() method

code:
                        <div class="spec">
                            <p id="one"></p>
                        </div>
                        <script>
                            var obj = { num: 2 };
                            function add(a, b){
                                return this.num + a + b;
                            }
                            document.getElementById("one").innerHTML = add.call(obj,3,5);
                        </script>
                

example: call() method applied on object literals

code:
                    <div class="spec">
                        <p id="two"></p>
                        <p id="three"></p>
                    </div>
                    <script>
                        const person = {
                            fullName: function() {
                                return this.firstName + " " + this.lastName;
                            }
                            }
                            const person1 = {
                                firstName:"Eveline",
                                lastName: "Quanten"
                            }
                            const person2 = {
                                firstName:"Astrid",
                                lastName: "Boonen"
                            }
                            document.getElementById("two").innerHTML = person.fullName.call(person1);
                            document.getElementById("three").innerHTML = person.fullName.call(person2);
                    </script>
                

example: use call() to chain object constructors

code:
                        <div class="spec">
                            <p id="four"></p>
                            <p id="five"></p>
                        </div>
                        <script>
                            function Product(name, price) {
                                this.name = name;
                                this.price = price;
                            }
                            function Food(name, price) {
                                Product.call(this, name, price);
                                this.category = 'food';
                            }
                            function Toy(name, price) {
                                Product.call(this, name, price);
                                this.category = 'toy';
                            }
                            const cheese = new Food('feta', 5);
                            const fun = new Toy('robot', 40);
                            document.getElementById("four").innerHTML = Object.entries(cheese);
                            document.getElementById("five").innerHTML = Object.entries(fun);
                        </script>
                

example: use call() to invoke an anonymous function

code:
                        <div class="spec">
                            <p id="six"></p>
                        </div>
                        <script>
                            const animals = [
                                { species: 'Lion', name: 'King' },
                                { species: 'Whale', name: 'Fail' }
                            ];
                
                            for (let i = 0; i < animals.length; i++) {
                                (function(i) {
                                    this.print = function() {
                                        document.getElementById("six").innerHTML += '#' + i + ' ' + this.species
                                                + ': ' + this.name +'<br>';
                                    }
                                    this.print();
                                }).call(animals[i], i);
                            }
                        </script>