Ad

I Did Not Bind My Function's "this" In The Constructor, But Why Isn't "this" Undefined?

- 1 answer

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

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad