CoursesGalaxy Courses Subscription Knowledge Hub
Knowledge Hub
Design Patterns


call(), apply() and bind() In JavaScript

In javascript a function is an object and every function has methods call(), apply and bind(). These methods are used to set the value of this. They are very useful to use this appropriately and in many other scenarios like Function Borrowing, Function Currying.

call()

call() method is used to invoke the function, it will pass an object as first parameter which will be the value of this inside function.


Syntax

functionName.call(objectName);

functionName.call(objectName, param1, param2,...);


Implementation

callDemo.js




Output




apply()

apply() method is same as call(). It is used to invoke the function but the parameters will be passed in array. This may be very useful in scenarios where we get the input in form of array or we have to pass variable number of arguments.


Syntax

functionName.apply(objectName);

functionName.apply(objectName, [param1, param2,...]);


Implementation

applyDemo.js




Output




bind()

bind() is used to create new function, it will pass an object as parameter which will be the value of this inside function.


Syntax

var bFunction = functionName.bind(objectName);

Implementation

bindDemo.js




Output





Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his course on Advanced JavaScript.







Yearly Subscription


Advanced JavaScript


Design Patterns Through JavaScript

Explore

Courses

Subscription

Knowledge Hub

Design Patterns

Tech Articles

About Us

Overview

Contact Us

CourseGalaxy

CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap between education and industry and provide the training on specific problems of industry to enhance the skills of Engineers in industry to do their job appropriately.

Learn From Us

2018 CourseGalaxy