JavaScript Function Call
The Javascript Function call is a predefined javascript method, that is used to write methods for different objects. It calls the method, taking the owner object as an argument. The keyword this refers to the “owner” of the function or the object it belongs to. All the functions in javascript are considered object methods. So we can bind a function to a particular object by using ‘call()’. A function will be the global object if the function is not considered a method of a JavaScript object.
Syntax:
call()
Return Value: It calls and returns a method with the owner object being the argument.
Example 1: Here is a basic example to describe the use of the call() method.
Javascript
<script> // function that returns product of two numbers function product(a, b) { return a * b; } // Calling product() function var result = product.call( this , 20, 5); console.log(result); </script> |
Output:
100
Example 2: This example describes the use of function calls with arguments.
Javascript
<p id= "GFG" ></p> <script> var employee = { details: function (designation, experience) { return this .name + " " + this .id + "<br>" + designation + "<br>" + experience; } } // Objects declaration var emp1 = { name: "A" , id: "123" , } var emp2 = { name: "B" , id: "456" , } var x = employee.details.call(emp2, "Manager" , "4 years" ); document.getElementById( "GFG" ).innerHTML = x; </script> |
Output:
B 456 Manager 4 years
Example 3: This example describes binding a function to an object.
Javascript
<script> var obj = {a: 12, b: 13}; function sum() { return this .a + this .b; } console.log(sum.call(obj)); </script> |
Output:
25
We have a complete list of Javascript Functions, to check those please go through the Javascript Function Complete reference article.
Supported Browser:
- Google Chrome 1.0
- Firefox 1.0
- Microsoft Edge 12.0
- Internet Explorer 5.5
- Opera 4.0
- Safari 1.0
Please Login to comment...