Topics
Javascript Call Apply Bind
By Saket Bhatnagar••Beginner to Intermediate
introduction
- 1Call , Apply and Bind methods are used to store the object reference in 'this' keyword of function.
- 2When function's 'this' have reference of object, then we can access states and behaviours of that object.
- 3
For practice we will use these objects as reference.
1let human1 = {2 name: "Chombi",3 age: 20,4};56let human2 = {7 name: "Dinga",8 age: 19,9};1011let human3 = {12 name: "Nimbi",13 age: 18,14};Below function we will use to access object's properties by using call, apply and bind methods.
1function detailsAll(a, b, c) {2 console.log("Name : " + this.name);3 console.log("Age : " + this.age);4 console.log("value of a : " + a);5 console.log("value of b : " + b);6 console.log("value of c : " + c);7}
call
- 1Call method accepts object reference as first argument And accepts 'n' number of arguments.
- 2 Here, arguments are passed to the function's parameter list.
- 3 It will call the function Immediately.
- 4
Example : Print name , age of object human1 and print function arguments.
1detailsAll.call(human1, 10,20,30);23Output -4Name : Chombi5Age : 206value of a : 107value of b : 208value of c : 30
apply
- 1Apply method accepts of 2 arguments where object reference is first argument and 2nd argument is the array of arguments.
- 2 Here arguments are passed to the function's parameters list.
- 3 It will call the function immediately
- 4
Example : Print name , age of object human2 and print function arguments.
1detailsAll.apply(human2,[11,22,33]);23Output -4Name : Dinga5Age : 196value of a : 117value of b : 228value of c : 33
bind
- 1Bind method accepts object reference as 1st argument and excepts 'n' number of arguments.
- 2 Here 'n' number of arguments are passed to the function's parameter list.
- 3 It will not call the function immediately.
- 4 It returns a new function in which 'this' Keyword is pointing to the object reference we have passed.
- 5 To execute the function we need function reference and parenthesis
- 6
Example : Print name , age of object human3 and print function arguments.
1let func = detailsAll.bind(human3, 77,88,99);2func();34Output -5Name : Nimbi6Age : 187value of a : 778value of b : 889value of c : 99