DEV Community

Cover image for  What is Function Binding? 💫
Allison Cortez
Allison Cortez

Posted on

What is Function Binding? 💫

When working with a regular function in JavaScript (not an arrow function), you'll find that when using the this context, you're referring to the object that invoked the function.

Sometimes, this ends up creating different results than what you'd expect.

Take the following example:

const Bob = {
  temperature: "45 degrees"
  sayNews() {
  console.log('It is ${this.temperature} outside!')
  }
}

setTimeout(Bob.sayNews, 1000) // It is undefined outside!
Enter fullscreen mode Exit fullscreen mode

You'll notice that we get undefined for the temperature variable. That's because when we refer to this in our setTimeout call, we are actually referring to the Window Object itself, and NOT Bob.

Are you confused yet?
So let's break this down.

  1. setTimeout called on Bob
  2. Inside Bob, in the sayNews function, this was referred to.
  3. Since setTimeout is a Window Object method, Javascript thinks that this is referring to the Window.

To fix this, we could do one of two things
Use .bind to specifically bind an object to a function

setTimeout(Bob.sayNews.bind(Bob) // It is 45 degrees outside!
Enter fullscreen mode Exit fullscreen mode

Use arrow functions, introduced in ES6

setTimeout(() => Dug.sayHi(), 1000) // It is 45 degrees outside!
Enter fullscreen mode Exit fullscreen mode

I hope this was helpful. Thanks for reading :)

Resources

Photo by Markus Spiske from Pexels

Top comments (2)

Collapse
 
ralphhovsepian profile image
Ralph Robert Hossepian

That was the easiest way to understand that.

Collapse
 
allisoncortez profile image
Allison Cortez

Thanks Ralph, I'm glad it was helpful!