'why do you need to bind a function in a constructor
I have a question relavent to this code: https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js
specifically:
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleRefreshClick = this.handleRefreshClick.bind(this)
}
I guess its a 2 part question.
- Why do I need to set handle change as an instance of class
this.handleChange =, can't I just use static functions for handleChange and call it directly with in the classonClick={handleRefreshClick}>? - I have no idea whats going on here:
this.handleRefreshClick.bind(this)
Thanks
Solution 1:[1]
Answered in reverse order...
this.handleRefreshClick.bind(something)returns a new function, in which references tothiswill refer tosomething. This is a way of saving the current value ofthis, which is in scope during the call to the constructor, so that it can be used later when the function is called.
- If your functions don't require access to the state of your component, then sure, you don't need to bind them.
The argument in favour of adding these lines to the constructor is so that the new bound functions are only created once per instance of the class. You could also use
onClick={this.handleRefreshClick.bind(this)}
or (ES6):
onClick={() => this.handleRefreshClick()}
but either of these methods will create a new function every time the component is re-rendered.
Solution 2:[2]
The reason why it's being done, is to bind the this keyword to that object. Like Tom said, calling a function from a class doesn't mean it's being called with the context of the object that created that function.
I think you might be getting confused because in the React examples/tutorials, using React.createClass() DOES bind this automatically for you. So you might be wondering why React.createClass() does it, but doesn't with ES6 class syntax.
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.
Hopefully that sheds some light on why that happens.
Solution 3:[3]
thisdepends how the function is called, not how/where it is created.
When you look at the code, you see two "this", why? Seems weird, right? The thing is it is not about how it seems. It is about how it is called.
You are basically saying. Hey, when somebody calls you remember this means this class. not something else.
When somebody calls your class like: x.yourClass().bind(this) you are saying this is not x but the class itself(with props and states etc.).
Quick note, even when you call directly the class like yourClass() you are actually calling window.yourClass() on browser, also that is why in this case the this is window.
Solution 4:[4]
These 2 functions handleChange and handleRefreshClick are passed down as props to other components ,
They are bind to this because when the child component will call these functions they will always execute with the APP context.
You can remove these functions from the class but still you need to bind this since you would be updating some parts of your APP
Solution 5:[5]
All the answers here are good, but for clarity regarding:
- I have no idea whats going on here:
this.handleRefreshClick.bind(this)
I think an example is best in describing the difference in behaviour.
// Class where functions are explicitly bound to "this" specific object
var Bindings = class {
constructor() {
this.Firstname = "Joe"
this.Surname = "Blow"
this.PrettyPrint = this.PrettyPrint.bind(this)
this.Print = this.Print.bind(this)
}
Print(inputStr) {
console.log(inputStr)
console.log(this)
}
PrettyPrint() {
this.Print(`${this.Firstname} ${this.Surname}`)
}
}
// Class where "this" context for each function is implicitly bound to
// the object the function is attached to / window / global
// identical class, except for removing the calls to .bind(this)
var NoBindings = class {
constructor() {
this.Firstname = "Joe"
this.Surname = "Blow"
}
Print(inputStr) {
console.log(inputStr)
console.log(this)
}
PrettyPrint() {
this.Print(`${this.Firstname} ${this.Surname}`)
}
}
var bindings = new Bindings()
var noBindings = new NoBindings()
bindings.PrettyPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow", PrettyPrint: PrettyPrint(), Print: Print() }
noBindings.PrettyPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow" }
// noBindings has both functions & everything works as we expect,
// if this is all you're doing, then there's practically little difference,
// but if we separate them from the original "this" context...
var b = { PPrint: bindings.PrettyPrint }
var nb = { PPrint: noBindings.PrettyPrint }
b.PPrint()
// > "Joe Blow"
// > Object { Firstname: "Joe", Surname: "Blow", PrettyPrint: PrettyPrint(), Print: Print() }
// PPrint calls "PrettyPrint" where "this" references the original "bindings" variable
// "bindings" has a function called "Print" which "PrettyPrint" calls
nb.PrettyPrint()
// > Uncaught TypeError: this.Print is not a function
// PPrint calls "PrettyPrint" where "this" references the new "nb" variable
// due to different "this" context, "nb" does not have a function called "Print", so it fails
// We can verify this by modifying "bindings" and seeing that it's reflected in "b"
bindings.Surname = "Schmo"
b.PPrint()
// > "Joe Schmo"
// > Object { Firstname: "Joe", Surname: "Schmo", PrettyPrint: PrettyPrint(), Print: Print() }
// We can also add a "Print" method to "nb", and see that it's called by PrettyPrint
nb.Print = function(inputStr) { console.log(inputStr); console.log(this) }
nb.PPrint()
// > undefined undefined
// > Object { PPrint: PrettyPrint(), Print: Print(inputStr) }
// The reason we get "undefined undefined",
// is because "nb" doesn't have a Firstname or Surname field.
// because, again, it's a different "this" context
Solution 6:[6]
I personally bind functions in constructor so that their references don't change on each re-render.
This is especially important if you are passing functions to read-only children that you don't need to get updated when their props don't change. I use react-addons-pure-render-mixin for that.
Otherwise, on each parent's re-render, binding will happen, new function reference will get created and passed to children, which is going to think that props have changed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | julianljk |
| Solution 3 | |
| Solution 4 | Piyush.kapoor |
| Solution 5 | |
| Solution 6 | Anton Kuzmin |
