Hey there!๐๐ป๐
I'm back again with a new javascript article. call(), bind() and apply() - you might have seen at least one of these three methods if you've spent quite some time in the Javascript realm. Well, maybe you're not using them that often in your day-to-day work but these are among the most frequently asked questions in any Javascript interview.๐คซ
Today is the day you learn them. ๐ช
In Javascript, functions are objects. Objects can have properties and methods. So, with every function, we get these three methods.
The call() and apply() methods set this
inside the function and immediately execute that function. The only difference between call() and apply() is that the apply() method accepts an array of arguments instead of comma-separated
values.
function.call(thisArg, arg1, agr2, ...)
function.apply(thisArg, [argumentsArr])
function.bind(thisArg, optionalArguments)
Revise "this"
in the case of functions.
BUT... before starting let's revise this
in case of functions. I have a dedicated blog on this
keyword only you can read it."this"keyword
When executing a function,
this
is determined by how a function is called(runtime binding).
const user = {
firstName: 'Chhakuli',
lastName: 'Zingare',
age: 21,
getIntro: function() {
console.log(`${this.firstName} ${this.lastName} is ${this.age} years old.`);
}
}
user.getIntro(); // "Chhakuli Zingare is 21 years old."
function randomFunc() {
console.log(this);
}
randomFunc(); // window object
- In an object method:
this
refers to the owner object. - In a function(sloppy mode): this refers to global object.
- In a function(strict mode): this is undefined.
That's enough knowledge for this.article
. ๐
Call() ๐ค
call(thisArg, arg1, arg2...)
: Call is a function with a provided this
. Further arguments are provided as a comma-separated
list.
Ways to remember: โCallโs arguments are separated by commasโ.
Let's understand this with a very simple example.
function userIntro() {
console.log(`${this.firstName} ${this.lastName}`);
};
const user = {
firstName: 'Samiksha',
lastName: 'Zingare'
};
userIntro(); // Output 1: undefined undefined
userIntro.call(user); // Output 2: Samiksha Zingare
userIntro.call({ firstName : 'Harry', lastName : 'Potter' }); // Output3: Harry Potter
Output:
- We have a function userIntro() that will try to access
this
and consolefirstName
andlastName
. We have three outputs: - We didn't use the call() method, so
this
by default will refer to thewindow
object. window object doesn't have any properties likefirstName
orlastName
. Hence, we gotundefined undefined.
- This time we use
call()
and pass an object that has the required properties. this will now beuser
. Hence, we get a favorable outputSamiksha Zingare
. - It's the same as above, just trying to prove how call() works. ๐
You can also pass additional arguments in call():
function userIntro(city, state) {
console.log(`${this.name} is from ${city}, ${state}`);
};
const user = {
name: 'Sam',
age: 21
}
userIntro.call(user, 'Nagpur', 'Maharashtra'); // Output: Sam is from Nagpur, Maharashtra
So, call()
a function with this
. ๐
bind()๐ผ
The bind function creates a copy of a function with a new value to the this present inside the calling function.
Ugh๐ฉ, too much information to process at once. But since now we understand call()
, let's use that knowledge to understand bind()
.
function getUser(user) {
console.log(`${ user } is from ${ this.state }.`);
}
getUser.call({ state : 'Maharashtra' }, 'Sam'); // Output 1: Sam is from Maharashtra.
const userFromMaharashtra = getUser.bind({ state : 'Maharashtra' });
userFromMaharashtra('Sam'); // Output 2: Sam is from Maharashtra.
userFromMaharashtra('Chhaku'); // Output 3: Chhaku is from Maharashtra.
We made a function getUser()
that is trying to access this
.
There are two outputs:
- We use
call()
and pass { state : 'Maharashtra' }(first argument) to be ourthis
. The second argument will beuser
. - We try to get the same output as 1 using bind().
- Using bind() we can bind
this
value to some function and get another function in return. - In our case, we bind it with { state : 'Maharashtra' } and store the returned function in
userFromMaharashtra
. - Now, when we call
userFromMaharashtra
, we just need to passuser
argument. It will already have athis
value. - Just calling the same function again with a different
user
.
So, what are the differences b/w call() and bind()?
call()
gets invoked immediately whereasbind()
returns a function that we can invoke later.call()
takes additional arguments butbind()
does not.call()
doesn't make a copy of the function unlikebind()
.
Heyyyy! We're almost done.๐
apply()๐ง
Apply()
does the exact same thing as call(), but it requires the original functionโs arguments to be passed in as an array.
function sum(num1, num2) {
console.log(this + num1 + num2);
}
sum.call(2, 3, 4); // Output: 9
sum.apply(2, [3, 4]); // Output: 9
So why would you ever use apply()?๐ค
Well, it depends on how youโd like your data to be shown. Having the arguments as an array can be useful for mathematical situations, or simply for making the separation between the โthisโ reference and the original function arguments easier to distinguish.
If this was useful, please hit the heart and feel free to follow and read my other articles.