DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

1

How to use bind() to bind a function to an object

In the previous post we discussed how - 'this' keyword works in JS.

But there was a problem we discovered;

Problem

when we call a function as a standalone object - or outside an object this will return the global object which is the window object in browsers, but we wanna return 'man' object (in this case)

Solution

using the bind function as shown below;


const man = {
  name: "rick",
  adventure() {
    console.log(this);
  }
};


const adventure_reference = man.adventure.bind(man);
adventure_reference();

Enter fullscreen mode Exit fullscreen mode

Output;

Alt Text

Explanation

  • Functions in JS are objects, they have properties and methods we can use.

    • this means adventure function in 'man.adventure' is an object and it has access to methods and properties - in this case we use bind () method
  • With the 'bind()' method we can set the value of 'this' permenantly.

  • When we call bind() under adventure() function we get a new function , And in that new function value of 'this' is based on the argument we pass in the bind method.


const adventure_reference = man.adventure.bind(what_we_pass_here_as_an_argument);

adventure_reference();

Enter fullscreen mode Exit fullscreen mode

'what_we_pass_here_as_an_argument' will determine the value of this ,
so when what_we_pass_here_as_an_argument is 'man' object, the bind method will return a new instance of the adventure function and set 'this' to point to the man object.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️