Call, Apply, bind methods in js
Call, apply and bind methods are some of the basic JS functions which are used to control the scoping of “this” keyword in JS.
Call->
imagine we have an object method, and and another object method wants to use the function from the first object method, but that function is only available in 1st one, the 2nd one can borrow that function from the first, using the call method.
eg:
let name={ "first":"Preeti", "last":"priya",fullname(){console.log(this.first+" "+this.last)};
let name2={ "first":"mridul", "last":"manas"}
name.fullname() //Preeti Priya
name.fullname(name2) //mridul manas
// so when we wanna use some function like this common , it could be defined separately,
fullname=()=>{
console.log(this.first+" "+this.last)
}
now,
fullname.call
(name);
fullname.call
(name2);
here, the first argument is the object to be called, other functional arguments can be passed as a string
Apply-> only differs with call in the way arguments are called
the n functional args are called in the form of an array
Only difference
Bind-> Returns a method binded to current object and then it can be invoked independently
looks similar to call method, but returns a function, not just invoke it
let newfunc=fullname.bind(name,"Swe");
console.log(newfunc);
it can now be invoked as a new func
newfunc();
Subscribe to my newsletter
Read articles from Preeti directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by