Working with “this” keyword in Javascript

This is confusing in all OOP programming languages but especially so in Javascript. When using callback functions, it’s not always apparent what the this keyword refers to.

The this keyword in React

In React, it’s even more confusing because this is used to reference the component context inside each class. Thankful there are a couple of options of how to handle this issue

1. Aliasing This

let component = this;
component.setState({
 loading: true
})
fetch(‘/‘).then( function loaded() {
 component.setState({
   loading: false
 })
})

This is easy for beginners to understand, but it feels very unnatural when working with JS.

2. Bind this

this.setState({
 loading: true,
})
fetch('/').then(function loaded() {
 this.setState({
   loading: false,
 })
}.bind(this))

All functions in javascript have the bind method available. However, trying to remember when to bind this can also get confusing.

3. React-specific: Using React Component Methods

React.createClass({
 componentWillMount: function() {
 this.setState({
   loading: true,
 });
fetch('/').then(this.loaded)
}
loaded: function loaded() {
 this.setState({
   loading: false,
 })
 }
})

This let’s you flatten your code and use named functions.

4. ES2015 Arrows

this.setState({
 loading: true,
})
fetch('/').then(() => {
 this.setState({
   loading: false,
 })
})

Arrow functions are elegant and always refer to the right context of this. Arrow functions are terser, include implicit returns, and refer to the right context of this no matter how many levels deep you are on your callbacks.

To learn more about arrow functions, check out Mozilla’s documentation.

The downside to using arrow functions is we lose the ability to use named functions. That can make debugging a real headache.

Just so you know, if you’re using Babel to compile ES2015 to ES5, then the compiler will use the “alias method” with arrow functions. That means it will compile to:

let _this = this;
_this.setState({
 loading: true
})
fetch(‘/‘).then( function loaded() {
 _this.setState({
   loading: false
 })
})

***
Credit for this outline goes to https://www.sitepoint.com/bind-javascripts-this-keyword-react/.

No Comments

Post a Comment