Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics (retired) Designing Data Flow Adding Players to the Scoreboard

Gonzalo Muro
Gonzalo Muro
5,281 Points

I dont understand yet what is the .bind(this) function for. Can you explain that to me please?

In the "Handling Events" section of the React Documentation, says the following:

// This binding is necessary to make this work in the callback this.handleClick = this.handleClick.bind(this);

, but why?

Is it because if we don't do that "this" will access only to his own scope (handleClick function) instead of the component scope?

"this" inside a function refers to an object, but which object it refers to depends on the how the function is called.

Consider the following example from "YDKJS"

function foo() {
    console.log( this.bar );
}

var bar = "global";

var obj1 = {
    bar: "obj1",
    foo: foo
};

var obj2 = {
    bar: "obj2"
};

// --------

foo();              // "global"
obj1.foo();         // "obj1"
foo.call( obj2 );   // "obj2"

You use bind() to create bounded methods and by binding this.handleClick to "this" , you make sure that no matter how you call your function the context remains the same.

As per the react documentation, they recommend binding your event handlers in the constructor so they are only bound once for every instance.