DEV Community

Discussion on: What's the worst part about the JS ecosystem?

Collapse
 
efpage profile image
Eckehard

There are lot´s of complains about the use of "this", which give people some headaches. For me, the worst thing about "this" is the use in classes. As any class variable and any class function is bound to "this", code inside a class is peppered with hundreds of "this".

On the other hand, function definitions inside a class do not need the "function" identifier. Writing longer class definitions you often get los to know, what precise class you are working on. I just started to add the class-name as a comment:

class test{
    myVar
    /*test*/myMethod(){ this.myVar = "Hello world" }
}
Enter fullscreen mode Exit fullscreen mode

It would be far more handy to have any class method clearly be part of the class like

class test{
   let myVar
   test.myMethod(){ myVar = "Hello world" }
}
Enter fullscreen mode Exit fullscreen mode

This yould also allow to shift some code into a class without the need to rewrite anything.

Collapse
 
michaelcurrin profile image
Michael Currin

Yeah this works differently in function and arrow function (not allowed in latter I think).

I found a video which explained this and there are some many cases where it behaves weird.

And then you assign var _this = this to get some context frozen...

Collapse
 
peerreynders profile image
peerreynders

there are some many cases where it behaves weird.

Don't expect JavaScript's 'this' to be a 'this' that you are already familiar with.

It's its own thing.

xkcd

Collapse
 
leob profile image
leob • Edited

In my view this, prototypal inheritance, constructors, and most of "classical" OO in Javascript is simply better avoided when designing new JS code. I much prefer a more FP (functional programming) style approach. Use objects, but just put data in those objects, then write functions that take in those objects as arguments and do something with them.

I know that almost every introduction about Javascript starts talking about this and about prototypal inheritance, but IMO it's a load of historical baggage that's confusing and almost always unnecessary. Just look at contemporary React (with function based components and with hooks, but without classes) and you can see that we don't really need classical OO, "this" and prototypal inheritance.

(use functional components and hooks in React and you'll almost never have to write "this")

Plain objects and functions get you there 90% of the time, prototypal inheritance is historical baggage. Javascript (especially ES6 with arrow functions, destructuring and so on) is a cool language, simply don't use its legacy features, that's all just cruft.