DEV Community

Discussion on: Is `this` in Javascript bad?

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
 
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
 
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