If this
is so difficult to reason about, why don't we just stop using it? Seriously. Why. don't. we. just. stop. using. it.?
If you have read How I rediscovered my love for JavaScript after throwing 90% of it in the trash, then you won't be surprised when I say I am throwing this
away. this
is gone. goodbye. this
won't be missed.
With functional JavaScript, you will almost never see this
. I say almost never because even though your code doesn't contain this
, you have little control over 3rd party libraries. Popular libraries like React, jQuery, eventemitter2 and many others will force this
down your throat.
Here are some examples of how libraries force us to use this
.
Forced this in React
// ๐ GROSS: this
class Counter extends React.Component {
constructor() {
super()
this.increment = this.increment.bind(this)
}
increment() {
this.setState(s => ({ count: s.count + 1 }))
}
render() {
return (
<div>
<button onClick={() => this.increment}>{this.state.count}</button>
<button onClick={this.increment.bind(this)}>{this.state.count}</button>
</div>
)
})
}
Forced this in jQuery
// ๐ GROSS: this
$('p').on('click', function() {
console.log($(this).text())
})
Forced this in eventemitter2
const events = new EventEmitter2({ wildcard: true })
// ๐ GROSS: this
events.on('button.*', function() {
console.log('event:', this.event)
})
events.emit('button.click')
this
is everywhere!
So what's the problem?
One problem is this
is not accessible if you use an arrow function. Sometimes I prefer to write an arrow function instead of a classic function
. Okay, I always prefer to write arrow functions.
Another problem is this
can be unintentionally reassigned. So your function might fail based on how others use it.
// WTF? these will produce different outputs
const say = cat => cat.speak() //=> "meow"
const say = ({ speak }) => speak() //=> Error: Cannot read property 'sound' of undefined
// WTF? these will produce different outputs
cat.speak() //=> "meow"
const speak = cat.speak
speak() //=> undefined
So let's just get rid of this
completely.
NO. THIS.
I created a simple function decorator that to get rid of this
. More on function decorators here.
After creating nothis
, I created a package so I can use it in all my projects.
So what would this look like you ask?
nothis this in React
import React from 'react'
import nothisAll from 'nothis/nothisAll'
// ๐ฅ LIT: no this in sight!
class Counter extends React.Component {
state = { count: 0 }
constructor() {
super()
nothisAll(this)
}
increment({ setState }) {
setState(({ count }) => ({ count: count + 1 }))
}
render({ increment, state }) {
return (
<div>
<button onClick={increment}>{state.count}</button>
</div>
)
}
}
nothis in jQuery
$('p').on('click', nothis(ctx => console.log($(ctx).text())))
nothis in eventemitter2
const events = new EventEmitter2({ wildcard: true })
// ๐ฅ LIT: nothis + destructuring!
events.on('button.*', nothis(({ event }) => console.log('event', event)))
events.emit('button.click')
But wait! There's more!
fixthis
can fix some of your existing this
rebinding problems!
import fixthis from 'nothis/fixthis'
const cat = {
sound: 'meow',
speak: function() {
return this.sound
}
}
// ๐ GROSS: this is unintentionally rebound
const speak = cat.speak;
speak() //=> Error: Cannot read property 'sound' of undefined
// ๐ฅ LIT: this stays this
const fixedCat = fixthis(cat)
const speak = fixedCat.speak;
speak() //=> "meow"
But I need help...
Install it...
npm install -P nothis
Add it to your libraries...
import nothis from 'nothis'
Play with it...
... and report bugs, request features or contribute to the project here https://github.com/joelnet/nothis.
This is the latest addition to my Rethinking JavaScript series. If this made you curious, check out a few of my other articles in this series:
- The if statement
- Death of the For Loop
- Replace break by going functional
- Eliminate the switch statement for better code
Hit me up on twitter with any questions @joelnet
Top comments (170)
I think finding a
nothis
orfixthis
in your code is far more terrifying than dealing withthis
. Interesting read nonethless.I agree... Overcomplicating something just because you're not a fan of something is worse than learning to use it correctly. You can't assign a cat.speak function to a variable and expect it to be callable like a normal function. Methods implicitly get passed the object when called, so cat.speak() implicitly passes cat to speak. When you assign the speak function to a variable and call it directly it can't pass the cat anymore and will fail. The correct way to call from the assigned variable is speak.apply(cat) which will do same thing as cat.speak(). This is basic common sense when you understand how the language works.
For sure, experienced JavaScript programmers are aware of this. But a lot of JavaScript programmers out there are not. And A LOT of people are still get tripped up on this today.
for instance this code:
Would any reasonable person understand that if you use argument restructuring, the context to
speak
will be reassigned?The best solution is to program without
this
. And when you program with a functional reactive style, you never have to usethis
, so you never have this problem.Though you are not in control of 3rd party libraries and there are many 3rd party libraries which will force you to use
this
and the problems associated with it.IMHO adding more libraries is worse for new developers. They won't know the difference between vanilla js functions and those of a library or framework.
Interesting concept but I'd prefer devs to learn the nuances of js.
Full disclosure: I'm a fan of vanilla js whenever possible.
To me this is as obvious as x=y not being same thing as x="y" but I do understand the confusion to novice programmers, even "y" is confusing to some. I'm just suggesting that the language should not go out of it's way to cater to novice programmers.
Agreed, JavaScript is weird. But I love it! I also love C#. They're different languages with different works and benefits.
The best solution is to program without
this
at all. The next best solution is to fully understandthis
. When those fail, this just an alternative.I agree that more people should favor vanilla JavaScript when possible.
To say
nothis
is for notice programmers, is to not understand all of the benefits that it can provide.nothis
will let you use argument destructuring.nothis
will let you use arrow functions.nothis
will name your context so you never have to writevar self = this
.nothis
will let you write pure functions that output is computed solely on the input of other functions.nothis
will let you use function composition.This is why I love JavaScript. JavaScript can be what you imagine it to be. If you imagine a JavaScript without
this
you can have a JavaScript withoutthis
.I'm happy you love JS, seriously. I think you have good intentions so as to provide the community with helpful utilities. I just wish that you would be more comfortable with
this
so you could see its use and benefits, especially leveraged with the fat arrow in particular.If I could suggest something, take a look at
apply
andcall
Function methods; that should provide some clarity. Going beyond that, I'm curious to see what would happen if I did something like this:I think people have been trying to force OOP into JavaScript for a long time. I actually think classes were a mistake in JavaScript. But now that classes exist, people feel more and more comfortable with OO techniques.
JavaScript has Prototypal inheritance which is different than Class inheritance. But people coming from other languages start using JavaScript as if it were Class inheritance and that is where a lot of issues come from.
I feel like JavaScript is better suited for a functional reactive paradigm. Which doesn't require
this
at all.The best solution is to code without
this
. Though sometimes you are stuck withthis
because of a 3rd library you are using.If you look at the source code of
nothis
you will actually find that is exactly what it is doing behind the scenes.apply
instead ofcall
. github.com/joelnet/nothis/blob/mas...So what you have suggested, is actually exactly how it works;)
There's no one best solution to every problem; what you're mentioning is subjective from case-to-case, dev-to-dev. You mention the use of functional reactive paradigm over OO, but then you're accessing
this.event
in your example;EventEmitter
doesn't currently endorse that.OO and Functional have their pros/cons and it's up to the infrastructure, architects, and developers to implement what works best as the solution to the problem, which is question to endless iterations of improvement over time.
We can sit here all day arguing about
this
, but I think it's clear where we both stand.Ciao
The project is early and in need of polish. It is also in need of contributors like you to provide these suggestions.
Based on feedback I have created a helper function that abstracts away a lot of this boiler plate. How does this code look?
Sorry, but I honestly laugh at
The irony is not lost on me. I have opened an issue for this github.com/joelnet/nothis/issues/3
Thanks!
Your feedback has been invaluable in the creation of nothis-react. You can now create a Component like this:
Thanks again!
It would make more sense with a more expressive usage like this, noMore(this), instead of
noThisAll(this)
,noThatAll(that)
and so on.noMore(fun)
,noMore(function)
...lol...I am the worst at naming. This was actually my first opened issue on github github.com/joelnet/nothis/issues/1 lol
noMore(this)
this makes sense when usingthis
, but doesn't if it wasnoMore(obj)
, which may happen.In my short experiencie with JavaScript, had never faced an issue while working with
this
. What is so bad about it?Don't worry, you will. Everyone does ;)
Check out this example:
You will also frequently run into problems with
this
when working with React.I have a few other examples on the github page github.com/joelnet/nothis
Those aren't problems to me, that's just not knowing how the language works. I don't mean to sound terse, but it's just never been an issue for me.
Exactly.
There are others who do have these problems. Because one individual does not have a problem does not mean a problem does not exist. A quick search on stack overflow will show a lot of people have difficulties understanding
this
.I don't think understanding
this
is not that hard.Besides, properly understand a language is a basic requirement to program in that language.
this
is a complicated concept to grasp and I'm sure there is room for improvement in its design; however, it is not broken and especially not broken to the point where we need wrapper libraries to unbind contexts. Arrow functions were created to pass the parent context (this
of the parent) into child scopes."Having difficulties" is part of learning process. That's how you grow.
I do not know a single developer that hasn't had to debug a
this
problem by writingconsole.log(this)
. It is not accepted that as a JavaScript developer, at some point you will have to debug `this.it doesn't have to be
Duh! Ofcourse you will. Just like with any other code that you're not sure about YET. Then as you debug it to get an insight, to see what
this
points to you'll ask yourself - wait a second how did that happened? Does that mean... OOOH! And then the spoon bends, the matrix code appears and you get it. And that my friend is one of the big pleasures of working with your head.It aint broken. Case closed.
Just FYI, saying case closed doesn't close the case.
You don't have to use the library. But please remember to think of me the next time you write
console.log(this)
.Arrow functions solve ONE of the problems with
this
.Here's a reference to
this
that you can't arrow function your way out of.nothis
also does more than removethis
. It lets you use arrow functions and also argument destructuring. Both of which are not options otherwise.What is the purpose of trying to access
this.event
on the 5th line? Ifthis.event
was a value declared in the parent scope, the fat arrow would actually save you. The implication of usingEventEmitter2
would be so that you can access arguments from the callback of theevents.on
method (ie. args passed inside the callback).The code is correct. This is how their API is written. I need the
this
from thefunction
inside theevents.on
method, not the parent scope.It works the same way jQuery's
this
context works here:You can't write an arrow function for these.
Actually,
jQuery
calls the callback of theelement
'sthis
passed into it viaapply
andcall
. Check it out: code.jquery.com/jquery-3.3.1.jsIn jquerys events
this
is the same asevent.delegateTarget
: api.jquery.com/event.delegateTarget/So you can use the arrow function to get access to the parent context and still access the element you have attached the listener to... Please don't stop using
this
just because you don't know how a lib works.No, not "everyone does". People who don't understand the language do. There is only an issue with
this
when you aren't aware of how scope worksPrecisely.
Which is A LOT of people! I'm not fabricating problems out of mid air. A very large number of people do have issues with
this
. You can tell by the number of articles written explaining the concept. The number of questions asked on stack overflow. Every JavaScript interview will include questions to see if you understand whatthis
is.It's a complicated subject for a lot of developers. I do not know a single developer that hasn't written
console.log(this)
at some point in their careers.The problem with
this
cannot be simplified into "that's just how scope works".This code is a good example of that. By simply using a destructured argument, the scope is unexpectedly changed.
The reason why this happens is explained when you fully understand
this
. But to many developers they will stumble onthis
. Just search stack overflow.So because it's something that people have to learn, that means it's a problem? No.
Arrow functions are designed to preserve scope. That's what they exist for. There is nothing "surprising" about them. Just people that haven't actually learned the language
YOU DONT DESIGN CODE AROUND "DEVELOPERS" THAT DONT UNDERSTAND THE LANGUAGE.
If it's something that a majority of developers stumble on, then yes it's a problem.
Much in the same way NULL has been described as the Billion dollar mistake. NULL is a MUCH more simple concept to grasp than
this
. Yet now because we decide to use null, we have introduced an entire class of bugs into our application. All those lovelyNullReferenceException
bugs.It doesn't matter how good of a programmer you are, YOU WILL run into
NullReferenceException
bugs.Of course, there are ways to program without NULL. And this would eliminate that entire class of bug from your application. But we don't (myself included).
If we can program in a way that can completely eliminate entire classes of bugs, why would we choose not do to so?
I had face a bad time debugging working with React, when the error was just forgot to bind
this
, but nothing really bad. But with TypeScript works the same way? Working with TS never had any problem.TypeScript is awesome. It definitely helps with
this
issues. The big problem of this in plain JavaScript is that you can never be sure what it really is. And your code may work differently based on how other people use it.These two pieces of code could yield different results because
this
becomes unintentionally rebound to a different context.So instead of worrying about what
this
is all the time, let's just get rid ofthis
completely and we never have to guess again.Oh, thanks for taking the time, to explain to me, to make it pretty clear. I used to think, problem was just about scope.
It is actually. it's just that your scope can change when you do not expect it to change.
So, is there any other options to avoid using this, that are native to JS? I know one of the quickest ways is
var self = this
, but not about anything that do not involves a variable. And one of your past comments, wake up my curiosity, if TypeScript is a superset of JS, what it does to work aroun withthis
issues?TypeScript doesn't fix all
this
issues.If you check out the REPL at typescriptlang.org/play/ and enter this code:
You'll find it still has problems with
this
.My solution to avoiding this is to write JavaScript functionally and not to mix data and functions together into classes.
I would instead write the above like this:
Although I can see what you are pointing, what is difficult, is to find the best way to avoid using
this
in a real application. Thanks a lot, this has been one of the most significant discussion this year.That is because you have been taught to use
this
. With OOP, you are pretty much stuck withthis
(unless of course you usenothis
). When you learn functional reactive programming, you'll findthis
to no longer be necessary and magicallythis
just vanishes from your codebase.Check out one of my projects here github.com/joelnet/bitcoin-all-tim.... This is a real world application. It follows what I preach from How I rediscovered my love for JavaScript after throwing 90% of it in the trash.
You won't find any references to
this
,var
,let
,if
,switch
,for
, thefunction
keyword or other staples of classic javascript programs.If you use typescript and modify the cat speak code to use an explicit if, you get a compile error.
It's pretty nice that this will happen at compile time and not runtime.
Not everyone does. I really think this is not an issue with
this
but an issue with people who insist on trying to write JS in an OOP style, perhaps because they came from an OOP background. The problem basically goes away when you use JS in a functional way, i.e. stop writing code which is called likeanimal.speak()
.I don't think it's too hard to still use
this
in the contexts where it's required by libraries without shooting yourself in the foot, and at the same time eliminate it from your own code.As mentioned by others, your invalid React code is really just an example of not understanding how the language works, and I don't think abstracting that away is a good solution.
^ THIS. This is the true solution. Write your software in a way that doesn't require the use of
this
ever.But there are many people that come from OOP and want JavaScript to be OOP. I have been trying to convince people to write functional code for a while now. But I still receive the "HOW DARE YOU" responses. OOPers gonna OOP.
I just hope they think of me every time they write
console.log(this)
:)Cheers!
A total gun ban also may prevent you from shooting yourself in the foot.
The funny thing is, I think you were trying to use this argument to show how silly it is to remove
this
. But a lot of people are seriously proposing total gun bans for this exact reason, accidental shootings. It's almost as if your statement can be interpreted as in agreement with the article...And banning guns will prevent a significant number of accidental gun deaths.
I get how it could trip up someone new to js, but that's what makes this a method and not just any old function.
Do you suggest replacing all classes with object factory functions?
Sure, s.speak is already bound.
Sure, memory and even code cache difference can be negligible when you don't instantiate even a thousand of these objects.
But what meaning does
const {speak} = s
have as a freestanding function?Should we have it a static function and not a closure and take a state POJO instead:
speak(s)
?I'll disagree with this statement.
null
is a much easier concept to understand when compared tothis
. Yetnull
is now currently considered to be the Billion dollar mistake or "The worst mistake in computer science".We all understand
null
and we understand it very well. Yet we are forever doomed to run into randomNullReferenceException
errors. Even though we fully understand and comprehendnull
, you can never guarantee you will not run into those bugs.So to assume problems with
this
are limited to Junior developers, I would say is an Optimism Bias.In my perfect world, Objects and behavior would be disconnected. So you would never have a function and data combined together. We would have Categories and Morphisms (transformations) and immutability.
Then the world becomes simplified:
And instead of encapsulating the state of a resource beyond our control in an object? IO monad?
How would you handle a
WebSocket
, aFile
handle, and such?null
is terrible. It shifts the job of knowing whether a function might return zero instead of one expected result to to the caller. And in JS we have two different nulls ๐TypeScript with
strictNullChecks
begins to solve this, but there's the risk that something external claiming to return one concrete value might return a nullish value at runtime.this
is quite different. There's a couple of rules, and once you get them it works perfectly:this
isn't special it's just the binding from the enclosing scope. (undefined
if that's nothing)undefined
if that's nothing)Function.protptype.{bind|call|apply}
firstget
the function, so it can't possibly be a method any more, so you get to provide your ownthis
bind
ed function forever loses those arguments, just like you can't rebind a curried function's argument you can't rebindthis
. All it really does isNo one could possibly be overwhelmed by this.
There are many ways properties are different from scope bindings.
For example, one would not expect
To have the same result as
Or consider getters and other capabilities of
Object.defineProperty()
Treating properties and bindings with the same expectations is a very novice thing in the context of JS.
On the other hand in this beginner period I can definitely appreciate, for example when using ES6 classes, that the methods would be forever bound to the
new
ed object.But once you see what that desugars to, one stops thinking that.
Probably a combination of event emitters and rxjs.
Check out a project of mine here where I use these techniques: github.com/joelnet/bitcoin-all-tim...
On this page you can see how I consume a WebSocket: github.com/joelnet/bitcoin-all-tim...
I'm am perplexed by your ability to understand the complexities of
null
and at the same time miss the complexities of a more simple concept beingthis
.What's the advantage of pointfree
propEq
usage? Isn't that less immediately readable thanx=>x.type==='match'
?I feel like passing key names around in strings is strictly worse and should be avoided whenever it can. So much so, that if you have to use index notation on a non-Array object because your name is truly dynamic, you should actually be using an ES6
Map
instead.I can see the top Event,
message
, has an excuse to useObservable
tofilter
, but why isnot just
And such?
Most importantly, how do you clean up the observables when the websocket closes? It seems that the
websocket
object and the three observables will never be collected, and a new call todefault
would just make a new one in parallel.I just got into the habbit of using it. I can go either way on this one. The advantage is when you use something like
path(['one', 'two', 'three'])
instead ofobj && obj.one && obj.one.two && obj.one.two.three
soprop
andpropEq
are similar which is why I used them.Just for consistency again. So all "subscriptions" have the same interface. Again, I could have gone either way.
If I remember correctly, I am handling this by exiting the app completely. I have another process that restarts it. I had some issues with closing / reopening some websockets and this app wasn't critical to stay open, so I hard exit.
you already have autobind(this) as a utility in react to prevent losing this context on event handlers which solves this issue in an easy and intuitive way without the need to bind everything manually.
i think your project is a nice idea considering how creative you got about solving that personal problem you got with this but on the other hand i think this is way to confusing to introduce in productive code bases.
handling this in js is not quite intuitive in some cases but there are only 2 - 3 tricky parts you gotta learn and this should be no problem at all.
autobind is a good tool too. It was created to solve one the problems with
this
.There are always easy ways to work with
this
. But you will always run into bugs with it. I am just trying to imagine a world where you never have bugs withthis
becausethis
doesn't exist.I have created a project to demonstrate how easy it can be to use React without
this
here: npmjs.com/package/nothis-reactIt looks like you know what you are doing in the
github.com/joelnet/nothis
package. Why are you falling into the traps ofthis
then?I see developers stumble on
this
. It's part of every developer interview process. Do they understand this?In a functional reactive program, you won't find any instance of this. But there are times when code is outside of your control. For example when you have to use a 3rd party library. So you can never be truly free.
But your question should not be ** Why are you falling into the traps of this then?** it should be ** Why do JavaScript developers fall into the traps of this?** To which you will have to google and search stack overflow to understand the complexity of why people don't fully understand
this
.It's mostly people incorrectly using the language when they say this has problems. It's pretty clearly defined as to what it does and where it's used. I use it all over my code with no issues at all.
If you're having so much of an issue with
this
, you don't understand JavaScript. Your scope can't "change when you don't expect it to" as you claim in a comment thread. YOU just aren't paying attention. I've literally never once had an issue with proper bindings. I bind or apply when needed, or use an arrow function when I need to keep a scopeYou seem to be suffering from the DunningโKruger effect. Just because you do not have a problem does not mean that others do not. A simple search on stack overflow or google will show
this
is a problem for many JavaScript developers.Take a look at this code:
By simply converting a function to use argument destructuring, you will cause the function to fail. It is not reasonable to assume this.
When you
bind
orapply
or use arrow functions to use the parent scope, these are all things that had to be learned. Not everyone is at that level. Do you remember WHY you had to learn those things?I do not know a single JavaScript developer that hasn't written
console.log(this)
to figure out WTFthis
is. And if you tell me you haven't, I'll call you a liar ;)Cheers!
this
is not surprising that it changes during destruction if you actually understand the language.Objects have their own
this
. Do you understand how destructuring works? It's absolutely reasonable to expect this to changeAbsolutely! There are very valid reasons why this is happening. And it goes all the way back to the early versions of JavaScript, back in the Netscape days before classes were introduced. I remember this because I have been programming in JavaScript for over 20 years now.
The ability to bind a
this
to a function made total sense back then. But then people tried doing OOP in JavaScript. People would attempt to make classes with Inheritance. JavaScript wasn't designed for that.Now we have an actual
class
, which I believe was a mistake to introduce to the language. Because when people seeclass
, they do not understand how it works under the hood. Class is just syntactic sugar after all. They incorrectly assume it will function in a similar way to how a class works in other languages.So sure, after you understand everything surrounding the concept of
this
, you will run into fewer bugs with it. But you are still going to run into bugs. I do not know a single developer that hasn't writtenconsole.log(this)
to figure out whatthis
is. "Oh it's window. Duh!"NULL is commonly referred to as the Billion dollar mistake. How much do you think
this
is going to cost us?Ridiculous. this isn't that bad, surely not bad enough to make such a big of deal over it. So, don't write an arrow function if you need to use this. It's not a big deal. Sure, the language should make it available on that situation and it's poor design that they didn't, but it's not the end of the world to use a different function form when necessary.
For experienced programmers,
this
isn't much of an issue. We are aware of the problems and how to correctly use it.Though for the rest of the JavaScript programmers that have yet to achieve that level of experience, they will surely stumble on
this
. (as stack overflow questions suggest).Bug with this are guaranteed. I have not seen a single JavaScript developer that hasn't written
console.log(this)
just to try and figure out WHAT IS THIS.The best solution is to not program with
this
at all. Use a functional reactive style.The library is just days old and needs a lot of work for sure. But take a look at this code (nothis v1.2.1). I would say this is more readable because of
nothis
.It's like any part of the language though. When I started hacking things together with jQuery, I'd occasionally copy paste a snippet with
this
included and I'd look at it for a few minutes and decide that I knew enough about what it did to do what I needed to do and made a mental note to file it away til later.Then I had to do something asynchronous in jQuery and using
$(this)
insidesetTimeout
broke what had worked just previously, so I deepened my understanding even further.And then I decided to learn some OOP and I got even better about reasoning about how the parameter
this
is assigned at call-time. Now I will only occasionally come across a weird case that I wasn't expecting. You might call this stockholm syndrome, that I've developed a forced affinity forthis
, but then again, we're literally writing poems for rocks that can think so what even is normal.I think once we've gained an understanding of
this
we forgot the journey it took to get there. We hold onto it as a badge of achievement. It's an accomplishment because it was so difficult. And now that we finally get it, why are we getting rid of it? After I spent all that time to finally learn it? Even knowing full well that we will run into issues with it again in our future.My journey with
this
has ended. I'm not gonna keep it around for nostalgia.My article How I rediscovered my love for JavaScript after throwing 90% of it in the trash might explain more of how I feel and why I am eliminating
this
.Not only am I going to run into edge cases with
this
in the future, but I'm going to have all sorts of problems with virtually every keyword in the javascript language at some point.But ultimately, i feel that once you get them, you get to a point where you can write cleaner, more legible code. Whether that's a tangible, quantifiable ability or an imaginary boyscout patch is another matter. As an example, before I knew you could do short circuit execution with the
&&
operator, I found code that employed it weird and unwieldy. Now it's a valuable tool I have to explain my ideas more precisely.I really liked the hackernoon article you've linked, and am inclined to agree more with some of the other points, (
var
is dead, RIPfor
) and if you're coming at it from a purely functional point of view, then I'd have to agree. But I still find plenty of ways to mess around with object oriented patterns every now and then, andthis
is a useful component when trying to reason about things in that way.I would disagree with this and the example I will provide is NULL. NULL is one of the simplest concepts to understand. So simple it could be the very first lesson of someone learning to program for the first time.
Yet NULL is now considered a THE WORST MISTAKE OF COMPUTER SCIENCE and is now being called The Billion Dollar Mistake.
We all understand NULL and yet we will be plagued with
NullReferenceException
's riddled throughout our code.Just because it is the status quo is not a valid reason to not change the status quo.
If we know the steps to take to eliminate entire classes of bugs, why are we so hesitant to take those steps?
If NULL is the Billion dollar mistake, how much is
this
going to cost us?It's an interesting idea, and as you say above, one of the reasons JS is now so ubiquitous is that you can mould the language in whatever shape you like just through coding style. I will, probably keep using
this
in my react components, and when doing anything that feels like it should be more object oriented, but it's great to have alternatives, and as functional dialects become more widely adopted, and thus more legible, I'm sure it's usage will probably decline anyway.While this is a really interesting thought exercise about how different language features affect the code we write I don't think it'll affect the code I write today.
Also, practically burst out laughing reading that article about
null
:Haha ya seriously. if NULL wasn't bad enough, we got stuck with two of them! lol
Two values that don't have values and one number that isn't a number. Again, we get paid to make arrangements of minerals dream about words we write. It's not related, but I feel like every conversation about coding should be had in this context.
Why instead of nothis dont you just use classes with arrow functions and ban function() and methods from your linter?
Sometimes you do not have control over the code you are using. An example of this would be 3rd party libraries.
I am forced to use
this
here because that is how the library is written.this prevents me from writing code like this
or like this:
But with
nothis
I can write my function like this:Alright, so nothis is great for serving as an adapter to third party code, but I think for own code using the es6 constructs like class, arrow function and e.g linter should suffice.
I would also prefer to use the nothis on the events object to fix all its methods at once.
Or imo better have another wrapping approach that hides the poor use of this in events.on, and the use of nothis, so that we dont have to repeat it, nor remember it each time we want to use events.on
Totally agree. Great suggestion. I just added a helper function to apply all functions at once.
What are your thoughts on this?
Great article! Completely agree with you.
Another library that bothers me by forcing the use of
this
is Mongoose, here's an example from its docs:There are also functions that you can't import and destructure, because of
this
.I would also like to add that
this
is an implicit argument for your functions, hence it can decrease the readability and comprehension of your code. BTW, that's why I hate using HOCs in React, it is hard to see how things relate to each other.I also noticed that in your bitcoin-all-time-high project you're using Moment.js, although it's a great library, I would like to recommend you a more functional friendly one: date-fns.
Thank you for writing!
Couldn't agree more. Render props partially fixes the problem but still you could get into pyramid of doom (unless you use a library like react-composer ๐)
And wow, bitcoin-all-time-high looks like a fun project. ๐ช
Totally agree. Render props is a great way to increase the visibility of your implementation by exposing values. I always go to a render props before a HOC.
It is a fun project. I can't wait for it to start tweeting again. Just gotta hit those all time highs again. lol
moment
has been my goto forever. So long in fact that I never bothered looking for another. date-fns looks very interesting. thanks for the recommendation, I'll check it out!This is very cool, and I understand the issue and your solution. However, my problem with it is readability. Isnt it a lot easier to reason about โfunction(){}โ than to perform the ceremony of calling notThisAll? Or fixThis?
Your proposal is really cool, it would take some getting used to. But if your worry is the novice developer, if they see this for the first time, they still have to lookup and understand what it means. Also, most code examples online will not have your library.
Iโd argue that the time spent debugging the annoying issues of โthisโ is time well spent! That way you learn the ins and outs of the language.
There are pro's and con's to everything in this world. So for me to say
nothis
doesn't come with a cost would be a lie. There is a cost for sure. And you have to weigh the pros and cons before considering it for a project. This should be true with every library, or even design pattern.Have a look at this:
Does that look complicated?
While I admire your creative solution and how calmly you are defending this idea, there are certain problems that you or any good person must acknowledge to better fight the
this
battle. I know my comment might get lost in this heated debate, but the majority of the comments talking aboutare ignorant and pompous ๐ฟ
I feel the best solution to the
this
problem, which others have pointed as well, is not using it at all. Your most common reply for that is({ speak }) => console.log(speak())
. I do agree that destructuring could be a disaster when dealing with context-sensitivethis
. But, I do not think that this problem is worthy enough to be dealt with an abstraction likenothisAll
. You can come up with such particular examples for other javascript problems as well. But in all of these cases, a practical and a wise solution is to just to be simply careful!You do not (generally) cover a problem by putting a blanket(abstraction) over it (which Javascript loves to do btw). You save the abstraction for complicated problems like DOM updates or routing. Abstractions never really are a pragmatic choice for bad choices Javascript creators made. The reason we have an arrow function is that there was a widespread
this
problem and everyone was inventing their own wheel to fix it.Your abstraction might work well for developers like you, who are well experienced with nitty-gritty details of
this
. A junior developer like me would find thenothisAll
too magical! Which in short would make me nervous about the code I am trying to modify. If I encounter athis
problem, I have fellow developers like you in my team to help me debug it, but I do not have fellow developers who have time to learn yet another abstraction after all the recent Javascript abstraction fatigue.Abstractions are great when used widely, for example, JSX or virtual DOM. The end of lifecycle for great abstraction generally is that they become first party API (jQuery) or the language syntax (fat arrow) offers a solution to the problem that they were trying to solve.
this
is very much a part of Javascript language and yes it is flawed! but simply ignoring it means you are ignoring a significant part of collective Javascript work done by fellow developers. Also, to be very honest, sometimes the most pragmatic solution to a problem is simply usingthis
.Lot of us don't have the luxury to work with fancy ES2015+ syntax and the web is built on the promise of backward compatibility. I see codebases which are full of advanced usage of
this
, which looks like (src code)Sure you can come up with ways to handle it in your abstraction, but no serious and widely used project would consider the novel abstraction because of the added complexity (which I like to call magic) over the already complex
this
.I do not want to sound against your idea, I very much like your creative approach. But if you ask me whether I would let my kids use it? My answer would be no.