Reputation:
I'm using React and Redux. I have a question. I know when I need "this" in a function I should bind
it. But without binding my code works. Why ?
Function :
onSubmit() {
this.props.dispatch({type: 'ADD_TO_LIST', payload: this.state.inputValue});
}
And this is my render input :
<input type="text" placeholder="Enter Your Text ..." onChange={(e) => {
this.setState({inputValue: e.target.value})}} onKeyDown={(e) => {
if (e.key === 'Enter') {
this.onSubmit()
}
}}/>
Upvotes: 1
Views: 66
Reputation: 104379
You have idea about "when binding is required", but you missed one thing, "calling function will have the this (object by which it was called)". The value of this
is determined by how a function is called.
Here:
this.onSubmit()
You are calling submit with this
(class instance), so this
(inside submit) will refer to class instance.
Check these references:
Why is JavaScript bind() necessary?
Upvotes: 1
Reputation: 67850
While function
is binding (it changes this
), ES6 arrow functions are non-binding. An example:
this.a = 1;
obj = {
a: 2,
bfunction: function() { return this.a; },
barrow: () => { return this.a; },
}
console.log(obj.bfunction()) // 2
console.log(obj.barrow()) // 1
Upvotes: 0
Reputation: 2925
Because you used an arrow function to call it, it's not the event handler itself. The arrow function is already bound correctly.
Upvotes: 0