Use apply function to call a function in JavaScript

Description

The following code shows how to use apply function to call a function.

Example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sum(num1, num2){<!--   www . j  a v a 2  s.  co m-->
return num1 + num2;
}

function callSum1(num1, num2){
return sum.apply(this, arguments);
//passing in arguments object
}

function callSum2(num1, num2){
return sum.apply(this, [num1, num2]); //passing in array
}
document.writeln(callSum1(10,10)); //20
document.writeln(callSum2(10,10)); //20


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

Click to view the demo

The code above generates the following result.

Use apply function to call a function in JavaScript