DEV Community

Discussion on: Is `this` in Javascript bad?

Collapse
 
nbageek profile image
Patrick Minton

I mostly agree with your friend, and I think ES6 has made it worse, because of how anonymous functions "break" the rules, which just confuses the hell out of junior devs:

foo: () => {
  // `this` isn't in `foo`'s context, it's in `foo`'s parent context.
}

I also kind of hate how everyone invents their own convention for re-assigning this to avoid context problems like so:

const that = this; // But some folks use `self`, or `_this`, or `this2`, etc.

const foo = function() {
  // do something with `that` here, since `this` is local to `foo`.
}

Having said that, it's use is extremely prevalent, so I wouldn't make a crusade of this. It's a lot being that guy who's always complaining that everyone uses the phrase "begging the question" wrong.

Collapse
 
nektro profile image
Meghan (she/her) • Edited

Arrow functions were made specifically so that the second example wouldn't have to happen anymore. Consider the following.

class Person {
    constructor(id) {
        console.log(this) // person
        const that = this;
        fetch(`https://api.acme.corp/people/${id}`)
        .then(x => x.json())
        .then(x => {
            console.log(this) // person
            Object.assign(this, x);
        })
        .then(function(x) {
            console.log(this) // window
            // `that` is the only reference to person in this scope
        });
    }
}
const person = new Person('12');

Ignoring how terrible that code is, arrow functions allow you to have functions in functions while still maintaining the scope of your parent, yes but this behavior was very much requested and intended

Collapse
 
nbageek profile image
Patrick Minton

I agree that this is a good thing....if you are senior enough at javascript to understand the nuances of the scope of this and you understand how arrow functions interact with this differently than "traditional" ones -- to many junior devs, () => is just shorthand for function(). The fact that it isn't is mostly the fault of this -- and is that extra "thing you need to know" really worth keeping this around?

I've always had a love/hate relationship with magic variables (back when I first encounterd $_ in perl my mind was a little blown).

I can completely understand how avoiding them makes for more readable code.

Thread Thread
 
nektro profile image
Meghan (she/her)

Using this in any language is a hallmark of doing anything in OOP. Yes, JS has some things to watch out for, but the idea anyone would consider trying to drop using this altogether instead of learning the time/place and make making great things so much easier escapes me.