Skip to content

JavaScript Function call() | Code

  • by

The JavaScript Function call() method calls a function with a given this value and arguments provided individually.

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

Note: By default, in a function this refers to the global object i.e, window in web browsers and global in node.js.

JavaScript Function call()

Simple example code With and Without Using call() Method.

<!DOCTYPE html>
<html>
<body>
  <script>

    // function that finds product of two numbers
    function product(a, b) {
      return a * b;
    }

    // without
    let result1 = product(100, 200);
    console.log("Wihtout call() method: " + result1);

    // call() method
    let result2 = product.call(this, 100, 200);
    console.log("Using call() method: " + result2);

  </script>
</body>
</html>

Output:

JavaScript Function call()

More Examples

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);// "cheese"

Do comment if you have any doubts or suggestions on this JS function tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading