Use function.call() to call a function in JavaScript

Description

The following code shows how to use function.call() to call a function.

Example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sum(num1, num2){<!--from   w w  w .j  av  a 2  s .  c om-->
return num1 + num2;
}
function callSum(num1, num2){
return sum.call(this, num1, num2);
}
document.writeln(callSum(10,10)); //20


window.color = "A";
var o = { color: "B" };
function sayColor(){
document.writeln(this.color);
}
sayColor(); //A
sayColor.call(this); //A
sayColor.call(window); //A
sayColor.call(o); //B


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

Click to view the demo

The code above generates the following result.

Use function.call() to call a function in JavaScript