user6571878
user6571878

Reputation:

Why function works without "this" binding?

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

Answers (3)

Mayank Shukla
Mayank Shukla

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:

MDN Doc

Why is JavaScript bind() necessary?

Upvotes: 1

tokland
tokland

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

timotgl
timotgl

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

Related Questions