loading...

re: Is `this` in Javascript bad? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: 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 h...
 

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

 

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.

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.

Code of Conduct Report abuse