Hey Jannik! I'm glad you liked it.
As for the usage, it is mostly up to your preference. In addition to what Jake covered (for arguments), you can use call and apply to give this inside a function a different object.
const someObj = {
name: 'iggy',
sayName() {
console.log(`The name is ${this.name}`)
}
}
Normally I'd do someObj.sayName(). But if one day I go back to reuse sayName, but I want to pass it a different name, you can just use call/apply. someObj.sayName.call({name: 'Russell'}).
It's like inheriting and reusing other object's properties.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Love the simplicity and especially the trick about how to remember the difference.
But I am missing the part "When to use call and when to use apply", which I was most interested in ;-) Is it just about preference?
It just depends on the structure of your arguments.
call
is useful for manually calling a function where you have explicitly defined arguments.But sometimes you have an array of arguments and you want to programmatically call a function with them, that's where
apply
is useful.That said, with the advent of the spread/rest operator (
...
),apply
is redundant.Hey Jannik! I'm glad you liked it.
As for the usage, it is mostly up to your preference. In addition to what Jake covered (for arguments), you can use
call
andapply
to givethis
inside a function a different object.Normally I'd do
someObj.sayName()
. But if one day I go back to reusesayName
, but I want to pass it a different name, you can just use call/apply.someObj.sayName.call({name: 'Russell'})
.It's like inheriting and reusing other object's properties.