This is the third and final post of my three part series on JavaScript's bind(), apply() and call()
.
Here is the JavaScript MDN explanation of call()
:
The call() method calls a function with
a given this value and arguments provided individually.
apply()
and call()
are relatively similar. Both immediately invoke a function (with a specified context for this
), where bind()
does not. The difference lies in the arguments. apply()
allows for arguments to be passed in as an array and call()
needs arguments to be passed in one by one.
As we learned in the previous parts of this series and by brushing up on this
, using the this
keyword without context results in undefined
.
const snowPerson = {
top: "small snowball",
middle: "medium snowball",
bottom: "large snowball",
accessories: "sticks, coal, scarf, hat and a carrot"
}
function buildSnowPerson() {
return `Stack ${this.middle} on top of ${this.bottom}
and stack ${this.top} on ${this.middle}.
Use ${this. accessories} to finish your snow person!`
}
If we invoke buildSnowPerson()
, it will return:
Stack undefined on top of undefined and stack undefined on undefined. Use undefined to finish your snow person!
Yikes. Looks more like a government document than it does instructions to build a snow person!
But, if we use call()
, buildSnowPerson.call(snowPerson)
we'll get some pretty good directions to build a snow person!
Stack medium snowball on top of big snowball and stack small snowball on medium snowball. Use sticks, coal, scarf, hat and a carrot to finish your snow person!
When we're using call()
, the snowPerson
object used as the argument becomes our this
.
Here's an example of using additional arguments with call()
:
function snowPersonSeason(hot, cold) {
return `If it's ${cold}, you can build a snow person like this:
Stack ${this.middle} on top of ${this.bottom}
and stack ${this.top} on ${this.middle}.
Use ${this. accessories} to finish your snow person!
This won't work if it's ${hot} time! `
}
Can you guess what snowPersonSeason.call('Summer', 'Winter')
will return?
If it's Winter, you can build a snow person like this:
Stack medium snowball on top of big snowball
and stack small snowball on medium snowball.
Use sticks, coal, scarf, hat and a carrot to
finish your snow person!
This won't work if it's Summer time!
Those are the basics of call()
!
Top comments (0)