April 12, 2021

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() {
   console.log(this.var)
}, this));

Useful for Magento developers. See more about jquery proxy

The underscore way


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

function doSomethingAfterClick() {
    console.log(this.var)
}
document.addEventListener('click', _.bind(doSomethingAfterClick, this));

Useful for Magento developers. See more about underscore bind method


“Red River” Howard Hawks 1948

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara