JavaScript apply() Function

You are Here:

JavaScript apply() Function

The apply() function calls a function or method as if it belonged to thisObj and passes an array of arguments to the function or method.

Note: The call() function passes the arguments individually. Whereas, the apply() function passes an array of arguments.

Basic Example

The following is the basic example to be understood before proceeding with a apply() function.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var bike = { brand : "Honda", model : "CB1000R", detail : function(){ return this.brand + " " + this.model; } } x.innerText = bike.detail(); </script> </body> </html>

Syntax

function.apply(Object, [argsArray])

Parameter Values

ValueTypeExplanation
ObjectOptionalThe value of thisObj provided for the call to a function.
argsArrayOptionalArray of arguments for the function.

apply() with Object and without Arguments

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var bike = { detail : function(){ return this.brand + " " + this.model; } } var bike1 = { brand : "Harley Davidson", model : "FAT BOB", } var bike2 = { brand : "Yamaha", model : "MT-09", } x.innerText = bike.detail.apply(bike2); </script> </body> </html>

apply() with Object and Arguments

Note: An array of arguments is passed instead of individual arguments.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var bike = { detail : function(color, price){ return this.brand +" "+ this.model +" "+ color +" "+ price; } } var bike1 = { brand : "Harley Davidson", model : "FAT BOB", } var bike2 ={ brand : "Yamaha", model : "MT-09", } x.innerText = bike.detail.apply(bike2, ["Red", "$15592"]); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author