Skip to content

Call() method in JavaScript

  • by

Call() method is predefined method in JavaScript. JavaScript call() method calls the function with a given this value and arguments provided individually.

func.call(thisArg, arg1, ... argN)

You can write a method that can be used on different objects.

Call() method in JavaScript

Simple example code calls a function by passing this and specified values as arguments.

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

  function sum(a, b) {
    return a + b;
  }

  // calling sum() function  
  var result = sum.call(this, 500, 10);

  console.log(result);
  console.log(typeof(sum))
</script>
</body>
</html>

Output:

Call() method in JavaScript

In the example below, this refers to the person object.

 <script>
  const person = {
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
  }
  const person1 = {
    firstName:"John",
    lastName: "King"
  }
  const person2 = {
    firstName:"Mary",
    lastName: "Doe"
  }

  person.fullName.call(person1);// John king
</script>

Do comment if you have any doubts or suggestions on this Js method 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

Your email address will not be published. Required fields are marked *