DEV Community

Is `this` in Javascript bad?

YCM Jason on March 03, 2018

Recently I have an argument with a friend who absolutely hate the this keyword in Javascript. He claims that since the language has an ambiguous bi...
Collapse
 
ben profile image
Ben Halpern

¯_(ツ)_/¯

Collapse
 
jonasroessum profile image
Jonas Røssum • Edited

here, I think you dropped this: \ (pun intended)

Collapse
 
2ezpz2plzme profile image
Steven Liao • Edited

One thing about the pattern that your friend advocates is that it would be harder to use instanceof.

function Car() {
  const car = {};

  car.position = 0;

  car.move = () => car.position++;

  return car;
}

const car = new Car();

console.log(car instanceof Car); // false

You would have to do:

Object.setPrototypeOf(car, Car.prototype);

console.log(car instanceof Car); // true
Collapse
 
dmfay profile image
Dian Fay

It's sneaky. I've wasted a decent amount of time and effort due to forgetting that this isn't bound in fat-arrow functions, or having a different binding than I expect at whatever point in the code. I still like using this, but I'm not sure I could mount a bulletproof defense of it.

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.

Collapse
 
damcosset profile image
Damien Cosset

I think I agree with your friend. I don't hate the this keyword, I use it quite a lot myself. But I feel like the keyword this is prone to more errors than code trying to avoid it. Obviously, it all depends on the programmers writing the code.

To me, it seems safer to try to avoid using too much this. It also reads better I believe. When I'm reading code, I wouldn't want to ask myself every 2 lines: What is this this referring to?

Collapse
 
ycmjason profile image
YCM Jason

This I think really depend on the design of your system.

In angular/vue/react, the framework seem to have developed around the keyword this without an issue. I wonder why they have made this choice if this could be troublesome.

Collapse
 
damcosset profile image
Damien Cosset

I use React quite often. So, I use this a lot. I use arrow functions all the time, so every single this I use refers to the outer most instance, the component, every single time. Definitely a personal preference anyway :)

Thread Thread
 
ycmjason profile image
YCM Jason • Edited

the only advantage that I could think of using this is the ability of reusing functions. Using the method suggested by my friend will create a new function instance for every object created. But if we use class, essentially we are using prototype, so all the methods will only be defined once. It makes a difference when we are creating the same instance many many times.

Thread Thread
 
gmartigny profile image
Guillaume Martigny

It completely shatter the prototype which is bad IMO. Your friend's method not only create a new function each time, but prevent any ineritance.
Also, it's not possible to supercharge Car's prototype.

The "this" keyword can be tricky, but avoiding it leaves you in a land without OOP.

Collapse
 
eebbann profile image
Eban Emmanuel

that was. mostly for the class base component i suppose

Collapse
 
hrmny profile image
Leah

Yeah, but in react click handlers and other stuff most of the time need this, which leads to you either abusing class properties for arrow functions or having bind everywhere

Collapse
 
nektro profile image
Meghan (she/her)

While there are some historical gotcha's when using this in certain contexts, if you plan to use JavaScript in an OOP sort of way, I would in no way say that you should steer away from using this. On top of that, constructors should not be defined with functions anymore. They should be in a class where using new is forced and the meaning of this is unambiguous.

Secondly I would greatly avoid using .bind or .call as much as you can. Some of the easiest ways to lose track of this is using functions in this way..

Collapse
 
nichgalea profile image
Nicholas Galea

"since the language has an ambiguous binding of this in different situations"

Learn the situations, and use accordingly.

Refusing to learn how the tool you're using works will impede your work, or at minimum drastically reduces the quality of it.

I understand that JavaScript is "special" when compared to other languages, but working around it's eccentricities will only stop you from leveraging all that it has to offer.

Collapse
 
jesseditson profile image
Jesse Ditson

In javascript, there are no absolutes. Your friend is wrong if they believe a single pattern will always be correct. That being said, some guiding principles can be helpful:

  • this is valuable when you're working with a stateful object. You can ask yourself: is your object an instance of a "superclass", in that other instances of this object may exist and have different states? it's very likely that this is the right tool for the job. In fact, as of es6 the module pattern your friend uses should most likely be refactored to a class.

  • this could be considered dangerous when working with raw objects. If you find yourself using .bind a lot, or if you're calling this from inside a method of a non class-like object (e.g. you would never make more than one of the object/function), consider taking a more functional approach. With new Promises and arrow functions, functional javascript has become a lot more fun and readable.

This argument IMO is generally a hold-over from when javascript didn't have classes, so you had the option of either constructing using the module pattern like your friend, or using a function constructor and appending methods to the function's prototype. Nowadays, we don't have to argue because we have the class keyword.

Is this a minefield of possible mistakes in javascript? Absolutely not. It's part of the language, and gives us important OOP abilities. You should use it when appropriate!

Collapse
 
layflags profile image
Lay Flags

Have you seen Douglas Crockford's talk during Nordic.js 2014? There he said that he stopped using Object.create, new, this, etc. completely and instead uses the factory pattern for creating objects, similar to the pattern of your friend (around 25:00). After watching the video I tried it out and from then on I never missed these keywords. I rarely use the factory pattern nowadays, just if I really need it. Instead I try to code more functional

Collapse
 
jjwesterkamp profile image
Jeffrey Westerkamp • Edited

It is only when call, bind and apply are used for the wrong reasons - or excessively - that this starts to get unpredictable. In my opinion this is the exact thing that makes Javascript as powerful as it is.

this always points to the context of the call to the function within which the keyword is used.

Arrow functions do what they do because the above statement does not apply to them. Instead, they inherit their this value from their declaration context.

That's all there is to it. It is never arbitrary, nor should it be difficult to determine, where this points to. I think it's just a matter of awareness of the fact that you'll have to look for its value at the preceding call stack, instead of it's lexical scope.

Collapse
 
tadaboody profile image
Tomer

Because I come from the word of c++/python amd haven't done anything majorly oop in js this seems unpredictable to me. But I don't know how much you should optimize your code readability for language newcomers

Collapse
 
wormss profile image
WORMSS

Tell your friend to suck it up and get over it. You either have a flexible language, and deal with its looseness, or pick a stricter language, and deal with the lack of flexibility.

Collapse
 
ycmjason profile image
YCM Jason

that's not a great argument, but I like your thinking! xD

Collapse
 
scottishross profile image
Ross Henderson

I have no reason for it, nor do I use JS a lot in my work. But whenever I do I avoid using this, as I just feels too ambiguous. I like being very clear and direct in my code, and if that means I need an extra two lines, that's just the way I prefer it.

Though in a lot of cases it would have made things a lot easier for me.

Collapse
 
joshualjohnson profile image
Joshua Johnson

There are no ambiguous bindings for the keyword this. They are very predictable. Some frameworks decide to change the bindings and that is the issue.

Collapse
 
deceze profile image
David Zentgraf

I consider Javascript to be an experiment in which Brendan Eich tried a few new ideas, one of which is the behaviour of this. And unfortunately, it's one of the ideas that didn't work out so well. While the simplicity and flexibility of Javascript's object system is intriguing, and maybe this is a necessary part to make it work, as a programmer on a day to day basis the behaviour of this introduces more stumbling blocks than it adds benefits through flexibility.

Put another way, I've had to add more "superfluous" bind() calls to keep the context on a callback than I used the flexible re-binding mechanism to do something useful I couldn't have otherwise.

These kinds of things are only discoverable through longterm use, which Javascript didn't have the time to go through before being released into the wild, and now can't be fixed because backwards compatibility. But that's no reason to throw out the baby with the bathwater; just be aware of it.

Collapse
 
kshoultz profile image
Kevin

I've been used to its usage. If he doesn't like it, he can do what he likes. But there are well defined rules for this. He just needs to research and understand it. Don't just hate it because it doesn't make sense to you. Arrow functions and the traditional functions use this differently. It's actually pretty elegant. In my opinion.

Collapse
 
circleofconfusion profile image
Shane Knudsen

I'm generally avoiding the use of this in my code, but most of my code has been AngularJS, and we're very rarely using the object prototype in the first place. Rather than mix-in functions and inheritance, we're using factories and injecting them as dependencies into factories and controllers that depend upon them.

I do kind of have a pet peeve against const self = this; and have been removing it where I can. I feel like it's a symptom of Java developers that really really want to build a class.

That being said, I do sometimes wonder if I'm missing some cool use cases for this.

Collapse
 
rrackiewicz profile image
rrackiewicz • Edited

As long as you are using some other library/framework you will always have to deal with "this". At least we have arrow functions now to avoid the "that". MJP of Fun Fun Function fame on YouTube refers to this as a "clown rainbow trap." Watch here youtube.com/watch?v=ImwrezYhw4w.

However, if you are rolling your own solution you can eliminate "this" all together if you chose. Douglas Crockford has forsaken "this" youtube.com/watch?v=PSGEjv3Tqo0#t=.... Another opinion can be found here whatsroyupto.blogspot.com/2015/05/.... I believe this technique is called the "Revealing Module Pattern" addyosmani.com/resources/essential...

Collapse
 
brianmcbride profile image
Brian McBride • Edited

I'd like to share my insights, but I can't find the proper scope!

If only I had an easy way to find "this" topic. ;)

Let's all just agree to never "let self = this" as that's just bound to be selfish.

Collapse
 
jvarness profile image
Jake Varness

The this keyword does suck. Your friend is totally right lol. This is why you might see const self = this; in some JS and see self used more.

Collapse
 
ycmjason profile image
YCM Jason

const self = this is not solving the problem that this could be bound ambiguously. It is simply solving the problem where each function would have their own this. E.g.

function a () {
  const self = this;
  return function() {
    return self.x;
  }
}

a.call({ x: 3 })(); // 3

I like using bind to solve this problem tho:

function a () {
  return (function() {
    return this.x;
  }).bind(this);
}

a.call({ x: 3 })(); // 3

But of course the nicest way would be using arrow functions:

function a () {
  return () => this.x;
}

a.call({ x: 3 })(); // 3
Collapse
 
andrewmcguinness profile image
Andrew McGuinness

I do the same, but I wouldn't necessarily say it's bad to use 'this' if you understand how it works well enough. I just find it easier to avoid it than to work out whether I've got it right.

Collapse
 
lucasmonstro profile image
Lucas Silva

Switch to ts

Collapse
 
ycmjason profile image
YCM Jason

I am guessing when you do obj.fn in typescript, you still lose binding, no?

Collapse
 
orifiael profile image
Orifiael

Disagree, when you use code that clones and appends elements, handling the new elements can be done so dynamicly with 'this'.

Collapse
 
ycmjason profile image
YCM Jason

I don't understand. Can you elaborate what you mean? :)

Collapse
 
bangkokian profile image
Bangkokian • Edited

this is an example of a language shooting for maximum flexibility — and having maximum flexibility shoot you back.

Collapse
 
agustinm20 profile image
Agustin M.

Bad? Bad is not use OOP