0

My button has the following onClick function

<button
  onClick={() => this.onDismiss(item.objectID)}
  type="button"
>

I have an onDismiss function that filters a list and updates my react application. I did not bind the function's "this" to its constructor. I purposely commented the "this" binding out but the application still works. Does the ES6 arrow functions automatically bind the funciton's "this" to the class Component? Shouldn't I be getting undefined?

My codesandbox link

dev_el
  • 2,357
  • 5
  • 24
  • 55
  • 1
    You're calling the function using `this.` so its context will be set to whatever `this` is in that context. [More details](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – Titus Nov 14 '19 at 11:37

1 Answers1

1

The arrow function:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

That is why you do not need to bind the Component's scope to the function.

João Cunha
  • 9,929
  • 4
  • 40
  • 61