Why do I need to bind () a function inside a constructor?
constructor (props){
super(props);
this.funcao = this.funcao.bind(this);
}
could not bind () without using a constructor?
Why do I need to bind () a function inside a constructor?
constructor (props){
super(props);
this.funcao = this.funcao.bind(this);
}
could not bind () without using a constructor?
Keep in mind that if you write your functions in your class as arrow functions, you don't need to bind(this).. its automatic. You don't need to bind properties in your constructor because it already has a this keyword attached to it.
You don't have to bind the methods in the constructor, have a look at the the explanation below.
// Setup (mock)
class MyValue {
constructor(value) {
this.value = value;
}
log() {
console.log(this.value);
}
bindMethods() {
this.log = this.log.bind(this);
}
}
const value = new MyValue("Hello World!");
var onclick;
// Explanation
console.log("==== 1. ====");
// Normally when you call a function, you call it with
// a receiver. Meaning that it is called upon an object.
// The receiver is used to fill the `this` keyword.
//
// «receiver».«method name»(«params»)
//
value.log();
// In the line above `value` is the receiver and is used
// when you reference `this` in the `log` function.
console.log("==== 2. ====");
// However in React a function is often provided to an
// handler. For example:
//
// onclick={this.log}
//
// This could be compared to the following:
onclick = value.log;
// When the event is triggered the function is executed.
try {
onclick();
} catch (error) {
console.error(error.message);
}
// The above throws an error because the function is
// called without receiver. Meaning that `this` is
// `undefined`.
console.log("==== 3. ====");
// Binding a function pre-fills the `this` keywords.
// Allowing you to call the function without receiver.
onclick = value.log.bind(value);
onclick();
console.log("==== 4. ====");
// Another option is using an anonymous function to
// call the function with receiver.
onclick = () => value.log();
onclick();
console.log("==== 5. ====");
// Binding doesn't have to occur in the constructor,
// this can also be done by any other instance function.
// a.k.a. a method.
value.bindMethods();
// After binding the functions to the receiver you're
// able to call the method without receiver. (Since all
// `this` keywords are pre-filled.)
onclick = value.log;
onclick();
For more details about the this
keyword you should have a look through the MDN this
documentation.
Methods that don't make use of the this
keyword don't have to be bound.
The reason why you bind()
functions is because class methods are not bound to the class instance object, which in React's case, it means you don't have access to the component's state
or props
.
Use arrow functions to automatically bind to the instance object: funcao = () => {...}
And call it from anywhere inside your component like this: this.funcao()