DEV Community

Discussion on: Rethinking JavaScript: The complete elimination and eradication of JavaScript's this.

Collapse
 
josetorreschang profile image
jose-torres-chang

In my short experiencie with JavaScript, had never faced an issue while working with this. What is so bad about it?

Collapse
 
joelnet profile image
JavaScript Joel

Don't worry, you will. Everyone does ;)

Check out this example:

const cat = {
  sound: 'meow',
  speak: function() {
    return this.sound
  }
}

cat.speak() //=> "meow"

const speak = cat.speak;
speak(); //=> undefined

You will also frequently run into problems with this when working with React.

// INVALID REACT CODE
class Counter extends React.Component {
  increment() {
    this.setState(s => ({ count: s.count + 1 }))
  }

  render() {
    return (
      <div>
        <button onClick={this.increment}>{this.state.count}</button>
      </div>
    )
  })
}

I have a few other examples on the github page github.com/joelnet/nothis

Collapse
 
cschliesser profile image
Charlie Schliesser • Edited

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.

Thread Thread
 
chriscapaci profile image
Chris Capaci

Exactly.

Thread Thread
 
joelnet profile image
JavaScript Joel

Those aren't problems to me

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.

Thread Thread
 
maple3142 profile image
maple

I don't think understanding this is not that hard.
Besides, properly understand a language is a basic requirement to program in that language.

Thread Thread
 
zeddotes profile image
zeddotes

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.

Thread Thread
 
lightest profile image
Nikita Agafonov

"Having difficulties" is part of learning process. That's how you grow.

Thread Thread
 
joelnet profile image
JavaScript Joel

I do not know a single developer that hasn't had to debug a this problem by writing console.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

Thread Thread
 
lightest profile image
Nikita Agafonov

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.

Thread Thread
 
joelnet profile image
JavaScript Joel

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

 
joelnet profile image
JavaScript Joel

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.

import { EventEmitter2 } from 'eventemitter2'
const events = new EventEmitter2({ wildcard: true })

events.on('button.*', function() {
  console.log('event:', this.event)
})

events.emit('button.click')

nothis also does more than remove this. It lets you use arrow functions and also argument destructuring. Both of which are not options otherwise.

Thread Thread
 
zeddotes profile image
zeddotes

What is the purpose of trying to access this.event on the 5th line? If this.event was a value declared in the parent scope, the fat arrow would actually save you. The implication of using EventEmitter2 would be so that you can access arguments from the callback of the events.on method (ie. args passed inside the callback).

Thread Thread
 
joelnet profile image
JavaScript Joel

The code is correct. This is how their API is written. I need the this from the function inside the events.on method, not the parent scope.

It works the same way jQuery's this context works here:

$('p').on('click', function() {
  console.log($(this).text())
})

You can't write an arrow function for these.

Thread Thread
 
zeddotes profile image
zeddotes

Actually, jQuery calls the callback of the element's this passed into it via apply and call. Check it out: code.jquery.com/jquery-3.3.1.js

Thread Thread
 
benwick profile image
benwick

In jquerys events this is the same as event.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.

$('p').on('click', (evt) => {
  console.log($(evt.delegateTarget).text())
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
willydee profile image
Willy Schott

A total gun ban also may prevent you from shooting yourself in the foot.

Thread Thread
 
joelnet profile image
JavaScript Joel

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.

Collapse
 
theodesp profile image
Theofanis Despoudis • Edited

It looks like you know what you are doing in the github.com/joelnet/nothis package. Why are you falling into the traps of this then?

Thread Thread
 
joelnet profile image
JavaScript Joel

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.

Collapse
 
kimlongbtc profile image
KimLongUn

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.

Thread Thread
 
joelnet profile image
JavaScript Joel

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 with this because this 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-react

Collapse
 
josetorreschang profile image
jose-torres-chang

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.

Thread Thread
 
joelnet profile image
JavaScript Joel

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.

const cat = {
  sound: 'meow',
  speak: function() { return this.sound; }
}

const logSound1 = animal => console.log(animal.speak())
const logSound2 = ({ speak }) => console.log(speak())

logSound1(cat) //=> "meow"
logSound2(cat) //=> Cannot read property 'sound' of undefined.

So instead of worrying about what this is all the time, let's just get rid of this completely and we never have to guess again.

Thread Thread
 
josetorreschang profile image
jose-torres-chang

Oh, thanks for taking the time, to explain to me, to make it pretty clear. I used to think, problem was just about scope.

Thread Thread
 
joelnet profile image
JavaScript Joel

It is actually. it's just that your scope can change when you do not expect it to change.

Thread Thread
 
josetorreschang profile image
jose-torres-chang

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 with this issues?

Thread Thread
 
joelnet profile image
JavaScript Joel • Edited

TypeScript doesn't fix all this issues.

If you check out the REPL at typescriptlang.org/play/ and enter this code:

const cat = {
    sound: 'meow',
    speak() { return this.sound }
}

const speak = cat.speak
speak()

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:

const cat = {
  sound: 'meow',
}

const speak = ({ sound }) => sound
speak(cat) //=> "meow"
Thread Thread
 
josetorreschang profile image
jose-torres-chang

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.

Thread Thread
 
joelnet profile image
JavaScript Joel • Edited

That is because you have been taught to use this. With OOP, you are pretty much stuck with this (unless of course you use nothis). When you learn functional reactive programming, you'll find this to no longer be necessary and magically this 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, the function keyword or other staples of classic javascript programs.

Thread Thread
 
ilmtitan profile image
Jim Przybylinski • Edited

If you use typescript and modify the cat speak code to use an explicit if, you get a compile error.

const cat = {
    sound: 'meow',
    speak(this: {sound: string}) { return this.sound }
}

const speak = cat.speak
speak() // <= Compile error: void is not assignable to { sound: string }.
Thread Thread
 
joelnet profile image
JavaScript Joel

It's pretty nice that this will happen at compile time and not runtime.

Collapse
 
kvsm profile image
Kevin Smith 🏴󠁧󠁢󠁳󠁣󠁴󠁿 • Edited

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 like animal.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.

Thread Thread
 
joelnet profile image
JavaScript Joel

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 like animal.speak().

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

Collapse
 
sampsonprojects profile image
Sampson Crowley

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 works

Thread Thread
 
zeddotes profile image
zeddotes

Precisely.

Thread Thread
 
joelnet profile image
JavaScript Joel

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 what this 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.

const logSpeak = animal => console.log(animal.speak())
const logSpeak =({ speak }) => console.log(speak())

The reason why this happens is explained when you fully understand this. But to many developers they will stumble on this. Just search stack overflow.

Thread Thread
 
sampsonprojects profile image
Sampson Crowley • Edited

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.

Thread Thread
 
joelnet profile image
JavaScript Joel

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 lovely NullReferenceException 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?

Collapse
 
qm3ster profile image
Mihail Malo

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?

class ligma {
  constructor(prefix) {
    this.prefix = prefix
    this.counter = 0
    this.statement = "ligma"
  }
  speak() {
    return this.prefix + " " + this.statement + " " + this.counter++
  }
}
const sugma = prefix => {
  let counter = 0
  const statement = "sugma"
  return {
    speak() {
      return prefix + " " + statement + " " + counter++
    },
  }
}

const PRE = "Very nice"

const l = new ligma(PRE)
const s = sugma(PRE)

console.log(l.speak())
console.log(l.speak())
console.log(s.speak())
console.log(s.speak())

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

Thread Thread
 
joelnet profile image
JavaScript Joel

I get how it could trip up someone new to js

I'll disagree with this statement. null is a much easier concept to understand when compared to this. Yet null 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 random NullReferenceException errors. Even though we fully understand and comprehend null, 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.

Do you suggest replacing all classes with object factory functions?

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:

// data
const ligma = prefix => ({ prefix, counter: 0, statement: 'ligma' })
// behavior
const speak = ({ counter, ...rest }) =>
  ({ ...rest, counter: counter + 1 })

const l = ligma('Very nice')
console.log(speak(l))
Thread Thread
 
qm3ster profile image
Mihail Malo

And instead of encapsulating the state of a resource beyond our control in an object? IO monad?
How would you handle a WebSocket, a File handle, and such?

Thread Thread
 
qm3ster profile image
Mihail Malo

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:

  1. In arrow functions, this isn't special it's just the binding from the enclosing scope. (undefined if that's nothing)
  2. In all other functions, including the object method shorthand on an object literal or a class, it's the enclosing object (undefined if that's nothing)
  3. Function.protptype.{bind|call|apply} first get the function, so it can't possibly be a method any more, so you get to provide your own this
  4. A binded function forever loses those arguments, just like you can't rebind a curried function's argument you can't rebind this. All it really does is
  Function.prototype.bind = function(thisArg, ...args) {
    return (...args2) => this.apply(thisArg, args.concat(args2))
  }

No one could possibly be overwhelmed by this.

There are many ways properties are different from scope bindings.

For example, one would not expect

const a = {b:1}
a.b++
console.log(a)

To have the same result as

const a = {b:1}
let {b} = a
b++
console.log(a)

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 newed object.
But once you see what that desugars to, one stops thinking that.

Thread Thread
 
joelnet profile image
JavaScript Joel

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

Thread Thread
 
joelnet profile image
JavaScript Joel

No one could possibly be overwhelmed by this.

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 being this.

Thread Thread
 
qm3ster profile image
Mihail Malo

What's the advantage of pointfree propEq usage? Isn't that less immediately readable than x=>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 use Observable to filter, but why is

  Observable.fromEvent(websocket, 'error')
    .subscribe(err => events.emit('gdax.ERROR', { exchange, err }))

not just

  websocket.on('error', err => events.emit('gdax.ERROR', { exchange, err }))

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 to default would just make a new one in parallel.

Thread Thread
 
joelnet profile image
JavaScript Joel

What's the advantage of pointfree propEq usage?

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 of obj && obj.one && obj.one.two && obj.one.two.three so prop and propEq are similar which is why I used them.

I can see the top Event, message, has an excuse to use Observable to filter, but why is

Just for consistency again. So all "subscriptions" have the same interface. Again, I could have gone either way.

Most importantly, how do you clean up the observables when the websocket closes?

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.