A thousand ways to avoid writing 'that' thing

With ES6 and the arrow functions it has become very easy to control the value of the this keyword in javascript. But in the past managing the this scope was a real nightmare.

the most common solution was:

var that = this

Even when this didn’t have a global scope (and I can assure, it was not taken for granted) it was a pretty bad syntax. Especially because it was repeated many times within a single file.

So let’s see a list of ways to come up with more elegant syntax:

The vanilla legacy way

this.var = "I won't after this"

function doSomethingAfterClick() {
    console.log("Don't Ever Trust Anybody. " +  this.var)
document.addEventListener('click', doSomethingAfterClick.bind(this));

The .bind() method creates a new function that uses as a this keyword the one you are passing as an argument.

The ES6 way

this.var = "Who'll Stop Me?"

document.addEventListener('click', () => console.log(this.var));

The easiest way. Arrow functions don’t create a new scope.

The Jquery way

this.var = "Every Time You Turn Around expect to see me"

$(document).on('click', $.proxy(function() {
}, this));

See more about jquery proxy

The underscore way

this.var = "I'm gonna hang you"

function doSomethingAfterClick() {
document.addEventListener('click', _.bind(doSomethingAfterClick, this));

Useful for Magento developers. See more about underscore bind method

“The Hidden Fortress” Akira Kurosawa 1958

Irene Iaccio

Freelance web developer

Subscribe to the monthly digest!

I'll use your email only to send you the latest posts once a month.