JavaScript | Function Apply
The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array.
Syntax:
apply()
Return Value: It returns the method values of a given function.
Example 1: This example illustrates the apply() function without arguments.
<!DOCTYPE html> < html > < head > < title > JavaScript apply() Method without argument </ title > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 > JavaScript apply() Method </ h2 > < h4 > It displays the details of second student </ h4 > < p id = "GFG" ></ p > <!-- Script to use apply() method --> < script > var student = { details: function() { return this.name + "< br >" + this.class; } } var stud1 = { name:"Dinesh", class: "11th", } var stud2 = { name:"Vaibhav", class: "11th", } var x = student.details.apply(stud2); document.getElementById("GFG").innerHTML = x; </ script > </ body > </ html > |
Output:
Example 2: This example illustrates the apply() function with arguments.
<!DOCTYPE html> < html > < head > < title > JavaScript apply() Method with argument </ title > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 > JavaScript apply() Method </ h2 > < h4 > It displays the details of second student </ h4 > < p id = "GFG" ></ p > <!-- Script to use apply() method --> < script > var student = { details: function(section, rollnum) { return this.name + "< br >" + this.class + " " + section + "< br >" + rollnum; } } var stud1 = { name:"Dinesh", class: "11th", } var stud2 = { name:"Vaibhav", class: "11th", } var x = student.details.apply(stud2, ["A", "24"]); document.getElementById("GFG").innerHTML = x; </ script > </ body > </ html > |
Output:
Supported Browser:
- Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Internet Explorer 5.5 and above
- Opera 4 and above
- Safari 1 and above