I Did Not Bind My Function's "this" In The Constructor, But Why Isn't "this" Undefined?
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
Answer
The arrow function:
An arrow function does not have its own
this
. Thethis
value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching forthis
which is not present in current scope, an arrow function ends up finding thethis
from its enclosing scope.
That is why you do not need to bind the Component's scope to the function.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM