Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Invoking functions with call() and apply() in JavaScript
Following is the code for invoking functions with call() and apply() in JavaScript −
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Invoking functions with call() and apply()</h1>
<div class="result"></div>
<br />
<button class="Btn">Click Here</button>
<h3>Click on the above buttons to invoke functions with call() and apply()
method</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
function addNum(num1, num2, num3, num4) {
return num1 + num2 + num3 + num4;
}
function multiplyNum(num1, num2, num3, num4) {
return num1 * num2 * num3 * num4;
}
let arr = [22, 33, 44, 55];
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "Sum of the numbers = " + addNum.call(this, 22, 33, 44, 55) + "<br>";
resEle.innerHTML +="Multiplication of the array elements = " +multiplyNum.apply(this, arr) +"<br>";
});
</script>
</body>
</html>
Output

On clicking the ‘Click Here’ button −

Advertisements