this.something = this.something.bind(this)
What is the above line actually doing? I am a newbie so please give a elementary level of explanation(for my understanding) also in a technical way
this.something = this.something.bind(this)
What is the above line actually doing? I am a newbie so please give a elementary level of explanation(for my understanding) also in a technical way
Use of the JavaScript 'bind' method
bind
creates a new function that will have this set to the first parameter passed tobind()
.
This is necessary because in the DOM library and many parts of JavaScript the hidden/implicit this
function parameter is changed to point to different objects behind-the-scenes.
A good example concerns event-handlers in JavaScript, where the this
parameter is not what it seems:
HTML:
<button id="someButton" name="Bar">Hello</button>
JavaScript (run after DOM is loaded):
function Foo() {
this.name = "Foo";
}
Foo.prototype.eventHandler( event ) {
console.log( event.type ); // will always print "click"
console.log( this.name ); // will print either "Foo" or "Bar"
}
var button = document.getElementById("someButton"); // HTMLButton
var fooInstance = new Foo(); // fooInstance.name == "Foo"
button.addEventListener( 'click', fooInstance.eventHandler );
If you run this code and click the button and set a breakpoint in Foo.prototype.eventHandler
then you'll see that this.name
is "Bar"
and not "Foo"
- even though you passed in a reference to fooInstance.eventHandler
which surely knows about fooInstance
when invoked?
It doesn't.
This is because the DOM API changes the this
of fooInstance.eventHandler
to be the button
instance instead. I don't know the exact reason, but I believe it's related to maintaining backwards compatibility with old-school HTML-attribute based JavaScript event-handlers like these:
<button onclick="alert(this.name)" name="Baz">Click me</button>
(Where this
refers to the containing HTMLElement
)
So using .bind
overrides the library's changing of this
. You might think that as .bind(this)
returns another Function
that the this
parameter will be changed anyway, but in fact, it doesn't. This is because the Function
returned actually cannot have its this
member changed at all, unlike most Function
objects.
The use of foo = foo.bind(this)
isn't anything unique to ReactJS (it's part of JavaScript) but it is an idiom in ReactJS:
why do you need to bind a function in a constructor
This is because React didn't want to mess with ES6 specifications (binding this to functions from its class is not in the ES6 class spec), but at the same time, wanted to give its users the convenience of ES6 class syntax. You can read more about this below.