Last week, I covered bind() and this week I'll be going over apply()
.
First thing, this is how JavaScript's MDN describes apply()
:
The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
Let's say you just got a new job. There are a lot of new people to meet, so let's write some code that will make introducing yourself to everyone a little bit easier:
let aboutMe = {
firstName: "Joe",
lastName: "Coder",
job: "web developer"
}
function sayHello(greeting, message) {
return `${greeting}. I'm ${this.firstName} and I'm a
${this.job}. ${message}`
}
let introduction = sayHello.apply(aboutMe, ["Hello!", "It's nice to meet you!"])
console.log(introduction)
// returns "Hello! I'm Joe and I'm a web developer. It's nice to meet you!"
Can you guess what happens without apply?
let introduction = sayHello(aboutMe, ["Hello!", "It's nice to meet you!"])
console.log(introduction)
// returns [object Object]. I'm undefined and I'm a undefined. Hello!,It's nice to meet you!
It's a good thing we remembered to use apply()
or that would have been embarrassing.
That sounds pretty similar to bind()
, but remember: bind()
creates a new function and apply()
does not. If we were to try: console.log(introduction())
we would get an error that looks something like this: TypeError: introduction is not a function
apply()
is similar to call()
, which we'll be covering next week!
Top comments (0)